2018年6月27日 星期三

[C#] DateTime物件與UnixTimestamp、JavaTimestamp互轉

DateTime物件轉成UnixTimestamp:

public static long DateTimeToUnixTimestamp(DateTime date)
{
   DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
  long unixTimestamp = (date.ToUniversalTime().Ticks - dt.Ticks) / TimeSpan.TicksPerSecond;
  return unixTimestamp;
}

DateTime物件轉成JavaTimestamp:

public static long DateTimeToJavaTimestamp(DateTime date)
{
   DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
   long javaTimeStamp = (date.ToUniversalTime().Ticks - dt.Ticks) / TimeSpan.TicksPerMillisecond;
   return javaTimeStamp;
}

UnixTimestamp轉成DateTime物件:

public static DateTime UnixTimestampToDateTime(double unixTimeStamp)
{
   DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
   dt = dt.AddSeconds(unixTimeStamp).ToLocalTime();
   return dt;
}

JavaTimestamp轉成DateTime物件:

public static DateTime JavaTimestampToDateTime(double javaTimeStamp)
{
   DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
   dt = dt.AddMilliseconds(javaTimeStamp).ToLocalTime();
   return dt;
}

沒有留言:

張貼留言