Jump to content



Photo

Convert String to DateTime

asp.net 4.0 c# string to date

  • Please log in to reply
2 replies to this topic

#1 limok

limok

    Neowinian

  • Joined: 20-May 04
  • Location: Manchester, UK
  • OS: Windows 8.1
  • Phone: Galaxy S4, iPhone 5

Posted 13 February 2013 - 14:25

Hi,

I'm trying to convert a string into a date type. This is the wasy bit but I want to convert it into a US format from a GB format. The code I have is as follows

string date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
DateTime myDate = DateTime.ParseExact(date, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

myDate defaults back to the GB style date.

Thanks,


#2 OP limok

limok

    Neowinian

  • Joined: 20-May 04
  • Location: Manchester, UK
  • OS: Windows 8.1
  • Phone: Galaxy S4, iPhone 5

Posted 13 February 2013 - 16:40

Solved my problem, the reason I was trying to convert the Date was to update a sqlserver database with the date format it required. If anyone else comes across this problem you need to user sql parameters e.g.

string sqlstmt = "UPDATE [tablename] Set [dateColumn]=@Date"
SqlCommand sqlCmd = newSqlCommad(sqlstmt, [your sql connection]);
sqlCmd.Parameters.Add(new SqlParameter("@Date", SqlDbType.DateTime));
sqlCmd.Parameters["@Date"].Value = DateTime.Now;
sqlCmd.ExecuteNonQuery();
'where sqlCmd is the SqlCommand


#3 Andre S.

Andre S.

    Asik

  • Tech Issues Solved: 14
  • Joined: 26-October 05

Posted 18 February 2013 - 01:11

A DateTime doesn't have a set style, internally it's just a bunch of integers and longs that are completely independent from culture. It's only when you call ToString() that it produces a string representation, and you can control what culture that representation is in by passing the correct CultureInfo parameter - exactly like when you use Parse or ParseExact.