简体   繁体   中英

Convert date time string in dd/mm/yyyy to datetime format mm/dd/yyyy

There is an input from CSV file which is in dd/mm/yyyy format. I have to pass these date values to the stored procedure. I want to convert this to mm/dd/yyyy format before I bulkcopy it to the database table from the datatable in the c# code.

Should I do this in the code or in the stored procedure which I am sending it to? Please advise.I have tried all possible combinations.

You could you use DateTime.ParseExact ,

var parsedDate = DateTime.ParseExact(dateString, "dd/MM/YYYY", CultureInfo.InvariantCulture);

where dateString is the string representation of the date you want to parse.

If your stored procedures expects a DateTime you could use the parseDate value. Otherwise, if it expects a string in the format you mentioned, you can pass the following value:

parsedDate.ToString("MM/dd/YYYY")

您应该在C#中将值解析为DateTime并将此日期值传递给SQL客户端或ORM,而不必将其转换为字符串

If your SQL field type is set to either one of the date value types it is quite impossible to format the date according to your desire, since the database engine does not store the formatted value but the date value itself.

Make sure to parse the DateTime in-code before updating its value in the SQL database.

string date = "2000-02-02";
DateTime time = DateTime.Parse(date); // Will throw an exception if the date is invalid.

There's also the TryParse method available for you. It will make sure the date value you're trying to parse is indeed in the right format.

string input = "2000-02-02";
DateTime dateTime;
if (DateTime.TryParse(input, out dateTime))
{
    Console.WriteLine(dateTime);
}

After the storage you're more than welcome to select your preffered display format for your DateTime variable using one of the given formats (read link below for a full list of available formats).

https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

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