将DateTime.Now转换成cstTime,解决在linux与windows中相差8个小时的问题
/// <summary>
/// 将DateTime.Now转换成cstTime,解决在linux与windows中相差8个小时的问题
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static DateTime ToCstTime(this DateTime time)
{
return GetCstDateTime(time);
}
private static DateTime GetCstDateTime(DateTime time)
{
//Instant now = SystemClock.Instance.GetCurrentInstant();
Instant instant = Instant.FromDateTimeUtc(time.ToUniversalTime());
var shanghaiZone = DateTimeZoneProviders.Tzdb["Asia/Shanghai"];
return instant.InZone(shanghaiZone).ToDateTimeUnspecified();
}
DateTime时间格式转换为Unix时间戳格式,精确到毫秒
/// <summary>
/// DateTime时间格式转换为Unix时间戳格式,精确到毫秒
/// </summary>
/// <param name="time"> DateTime时间格式</param>
/// <returns>Unix时间戳格式</returns>
public static long ToUnixTimestamp(this System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (long)(time - startTime).TotalMilliseconds;
}
Unix时间戳转为C#格式时间
/// <summary>
/// Unix时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp">Unix时间戳格式,例如1482115779</param>
/// <returns>C#格式时间</returns>
public static DateTime GetTime(this System.DateTime time, string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
获取日期之间的天数
/// <summary>
/// 获取日期之间的天数
/// </summary>
/// <param name="dateStart"></param>
/// <param name="dateEnd"></param>
/// <returns></returns>
public static int DateDiff(DateTime dateStart, DateTime dateEnd)
{
DateTime start = Convert.ToDateTime(dateStart.ToShortDateString());
DateTime end = Convert.ToDateTime(dateEnd.ToShortDateString());
TimeSpan sp = end.Subtract(start);
return sp.Days;
}
网友评论