简体   繁体   中英

Datetime Conversion in C#

I receiving dates in the USA standard format mm/dd/yy .

I can upload to MySQL only in the format of yyyy-MM-dd .

How can you convert mm/dd/yy format to yyyy-MM-dd format in C#?

You could parse it and then format it. ( DateTime.ParseExact , DateTime.ToString )

However, you shouldn't have to reformat for MySQL's benefit, and it suggests your database access is inappropriate:

  • Your database column should be a DATETIME column or something similar, if you're storing dates in it
  • Your database code shouldn't be including the value as a string at all. It should be passing it as a parameter with a DateTime value

So using parameterized SQL, you should just need to parse (eg using DateTime.ParseExact ), then pass it up as a DateTime :

DateTime date = DateTime.ParseExact(text, "mm/dd/yy",
                                    CultureInfo.InvariantCulture);
command.Parameters.Add("@Foo", MySqlDbType.DateTime).Value = date;

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx ... please check here. you can convert the date format in C#

You can use MySQLs STR_TO_DATE(str,format) function.
Or you can use string formatting in c#

Something like this should work:

DateTime dt = Convert.ToDateTime(dateString);
string newDateString = dt.ToString("yyyy-MM-dd"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM