C# DateTime和String转换
string time = "20160202"; DateTime.ParseExact(time,"yyyyMMdd",System.Globalization.DateTimeFormatInfo.CurrentInfo);
结果:
{2016/2/2 0:00:00} Date: {2016/2/2 0:00:00} Day: 2 DayOfWeek: Tuesday DayOfYear: 33 Hour: 0 Kind: Unspecified Millisecond: 0 Minute: 0 Month: 2 Second: 0 Ticks: 635899680000000000 TimeOfDay: {00:00:00} Year: 2016
1
DateTime CreateTime = new DateTime(); 如果时间格式:"yyyy-MM-dd HH:mm" 例如:string t="2016-02-02 11:15"; 可以:DateTime.TryParse(t,out CreateTime); 也可以:Convert.ToDateTime(t);
结果:
{2016/2/2 11:15:00} Date: {2016/2/2 0:00:00} Day: 2 DayOfWeek: Tuesday DayOfYear: 33 Hour: 11 Kind: Unspecified Millisecond: 0 Minute: 15 Month: 2 Second: 0
补充:
如果这么写:
DateTime.ParseExact("20161027152800","yyyyMMddhhmmss",System.Globalization.DateTimeFormatInfo.CurrentInfo);
是会报错的:Message: "该字符串未被识别为有效的 DateTime。"
因为:
上面的写法只能识别12时计时法;想24时计时法转换的↓
DateTime.ParseExact("20161027152800","yyyyMMddHHmmss",System.Globalization.DateTimeFormatInfo.CurrentInfo);
hh和HH...........
哈哈