DateTimeHelper.cs

出自 ProgWiki
前往: 導覽搜尋

用途

  • PHP的Date("U")所產生的日期值與ASP.NET的DateTime的日期格式互轉

程式碼

using System;
 
public class DateTimeHelper
{
    static double CurrentTimeZoneUtcOffset = 99;
 
    static DateTime Timestamp2DateTime(double timestamp)
    {
        if (CurrentTimeZoneUtcOffset == 99)
            CurrentTimeZoneUtcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalHours;
 
        DateTime dt = (new DateTime(1970, 1, 1)).AddHours(offset).AddSeconds(timestamp);
 
        return dt;
    }
 
    static double DateTime2Timestamp(DateTime dt)
    {
        if (CurrentTimeZoneUtcOffset == 99)
            CurrentTimeZoneUtcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalHours;
 
        double timestamp = (dt.AddHours(-CurrentTimeZoneUtcOffset) - new DateTime(1970, 1, 1)).TotalSeconds;
 
        return timestamp;
    }
}