Welcome Guest! To access all forums & features, please register an account or sign-in. → Why register?



Convert String to DateTime


2 replies to this topic - - - - -

#1 limok

    Resident Elite

  • 1,167 posts
  • Joined: 20-May 04
  • Location: Manchester, UK
  • Phone: Lumia 800

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

    Resident Elite

  • 1,167 posts
  • Joined: 20-May 04
  • Location: Manchester, UK
  • Phone: Lumia 800

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 +Asik

  • 5,970 posts
  • 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.