- 时间转字符串
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"); // => 2016-05-09 13:09:55:235
通常实际应用中不考虑本地化问题时,以自定义方式转换比较常见
- 字符串转时间
var dt = Convert.ToDateTime("2017-02-01 12:09:35");
//----------------------------------------------------------------------------------------
//Convert.ToDateTime(string)中的string可以是各种格式,
//都能正常转换,非常好用,例如
var dt1 = Convert.ToDateTime("2017-2-2 12:02:22");
var dt2 = Convert.ToDateTime("9:2 2017-2-02");
Console.WriteLine(dt1.ToString("yyyy-MM-dd HH:mm:ss"));
Console.WriteLine(dt2.ToString("yyyy-MM-dd HH:mm:ss"));
//结果是
//2017-02-02 12:02:22
//2017-02-02 09:02:00
//-----------------------------------------------------------------------------------------
3.非常规字符串转时间
string dateString = "20110526131407";
DateTime dt = DateTime.ParseExact(dateString, "yyyyMMddHHmmss",
System.Globalization.CultureInfo..InvariantCulture);