首先,总结两个简单的方法,实现 秒 与 日期 的相互转换:
1 public class MyTest 2 { 3 /// <summary> 4 /// 将Unix时间戳转换为DateTime类型时间,12时计时法 5 /// </summary> 6 /// <param name="d">double 型数字</param> 7 /// <returns>DateTime</returns> 8 public static System.DateTime ConvertIntDateTime(double d) 9 { 10 System.DateTime time = System.DateTime.MinValue; 11 System.DateTime startTime = Convert.ToDateTime("1970-1-1 8:00:00"); 12 time = startTime.AddSeconds(d); 13 return time; 14 } 15 16 /// <summary> 17 /// 将Unix时间戳转换为DateTime类型时间,12时计时法 18 /// </summary> 19 /// <param name="d">int 型数字</param> 20 /// <returns>DateTime</returns> 21 public static System.DateTime ConvertIntDateTime(int d) 22 { 23 System.DateTime time = System.DateTime.MinValue; 24 System.DateTime startTime = Convert.ToDateTime("1970-1-1 8:00:00"); 25 time = startTime.AddSeconds(d); 26 return time; 27 } 28 29 /// <summary> 30 /// 将c# DateTime时间格式转换为Unix时间戳格式 31 /// </summary> 32 /// <param name="time">时间</param> 33 /// <returns>double</returns> 34 public static double ConvertDateTimeInt(System.DateTime time) 35 { 36 double intResult = 0; 37 System.DateTime startTime = Convert.ToDateTime("1970-1-1 8:00:00"); 38 intResult = (time - startTime).TotalSeconds; 39 return intResult; 40 } 41 }
假如有字符串 : ”2018-07-11 00:00:00“,使用 System.DateTime.Parse() 转换后的结果默认是 12 时计时法,结果: 7/11/2018 12:00:00 AM