【C#】時間日期格式轉換:long和DateTime相互轉換


// DateTime --> long
public static long ConvertDateTimeToLong(DateTime dt)
{
    DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
    TimeSpan toNow = dt.Subtract(dtStart);
    long timeStamp = toNow.Ticks;
    timeStamp = long.Parse(timeStamp.ToString().Substring(0, timeStamp.ToString().Length - 4));
    return timeStamp;
}


// long --> DateTime
public static DateTime ConvertLongToDateTime(long d)
{
    DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
    long lTime = long.Parse(d + "0000");
    TimeSpan toNow = new TimeSpan(lTime);
    DateTime dtResult = dtStart.Add(toNow);
    return dtResult;
}

測試 long –> DateTime:

string time = "1490782464000";
DateTime dt = TimeUtils.ConvertLongToDateTime(long.Parse(time ));
System.Console.WriteLine(dt.ToString());

輸出:

2017/3/29 星期三 下午 6:14:24


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM