• 0

Convert String to DateTime


Question

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);
[/CODE]

myDate defaults back to the GB style date.

Thanks,

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

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

Link to comment
Share on other sites

  • 0

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.

Link to comment
Share on other sites

This topic is now closed to further replies.