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

2

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

asked by anonymous 30.03.2014 / 21:59

2 answers

4

Here is an example that should help you, I'll copy it below to make it easier: Link .

How to convert a string to a DateTime (C # Programming Guide)

It is common for programs to allow users to enter dates as string values. To convert a date string based on an object System.DateTime you can use the method Convert.ToDateTime(String) or static method 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
*/
    
30.03.2014 / 22:21
3

If you need to interpret a specific culture-independent format, use the method DateTime.ParseExact method :

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

I've never used MySQL, but for SQL Server I would never use text (unless the date is saved as text in the database). It would use a SqlCommand with SqlParameter s.

    
01.04.2014 / 11:04