Convert Date dd/mm/yyyy to ISO 8601 format (yyyy-mm-dd)

Asked

Viewed 2,189 times

3

I have a field called maskedTextBox2 in C# Windows Form, which contains a date mask in the format dd/mm/aaaa. How can I convert this string format aaaa-mm-dd to save to Mysql database, which uses dates in ISO 8601 format (aaaa-mm-dd)?

  • 1

    You have tried using STR_TO_DATE? http://dev.mysql.com/doc/refman/5.7/en/date-and-timefunct-ions.html#function_str-to-date

  • had not tried yet, but it worked, vlw!

  • 1

    I edited to fix the date format. Mysql’s yyyy-mm-dd format is not English, but standardized according to ISO 8601.

  • http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

2 answers

5


Here is an example that should help you, I will copy it below to facilitate: Link.

How to convert a string into a Datetime (Programming Guide in C#)

It is common for programs to allow users to enter dates as string values. To convert a date string based on an object from System.DateTime, you can use the method of Convert.ToDateTime(String) or the static method of DateTime.Parse(String), as shown in the following example.

// Date strings are interpreted according to the current culture.
// If the culture is en-US, this is interpreted as "January 8, 2008",
// but if the user's computer is fr-FR, this is interpreted as "August 1, 2008"
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);            
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day);

// Specify exactly how to interpret the string.
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);

// Alternate choice: If the string has been input by an end user, you might 
// want to format it according to the current culture:
// IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture;
DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal);
Console.WriteLine("Year: {0}, Month: {1}, Day {2}", dt2.Year, dt2.Month, dt2.Day);

/* Output (assuming first culture is en-US and second is fr-FR):
Year: 2008, Month: 1, Day: 8
Year: 2008, Month: 8, Day 1
*/
  • It worked too, vlw!

  • @Augusto Blz, any doubt goes aew!

4

If you have to interpret a specific format independent of culture, use the Parseexact.Datetime method:

DateTime.ParseExact("01/04/2014", "dd/MM/yyyy", CultureInfo.InvariantCulture)

I never used Mysql, but for SQL Server I would never use text (unless the date is saved as text in the database). I would use a SqlCommand with SqlParameters.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.