简体   繁体   中英

Convert date string to a SQL readable date format

我正在尝试将日期字符串Oct 21 2014 1:00 AM2014-10-21 01:00:00或 SQL Server 可以理解的内容。

Use DateTime.TryParse

var dateString = "Oct 21 2014 1:00 AM";
DateTime result;
DateTime.TryParse(dateString, out result);
var sqlDate = result.ToString("yyyy-MM-dd HH:mm:ss");

I'd argue that if you're using ADO.NET to communicate with your SQL Server, you shouldn't use a formatted date string as a query parameter. You should instead use a DateTime object. You can get it from your string by using either the DateTime.Parse or DateTime.TryParse methods:

DateTime date = DateTime.Parse("Oct 21 2014 1:00 AM"); // Use this as your query parameter.

However if you do decide to go with using a formatted string, the simplest way would be first parse it to as shown above, then you can use ToString with a format string overload, to format your date as you want.

To get your example format:

DateTime date = DateTime.Parse("Oct 21 2014 1:00 AM");
string formatted = DateTime.ToString("yyyy-MM-dd hh:mm:ss"); // 2014-10-21 01:00:00

Please see answer here.

Converting a String to DateTime

DateTime.ParseExact may work for you to convert in DateTime and then you can use ToString(<format>) with format to convert it in required string.

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