DateTime與long互轉


DateTime轉long:

public static long GetDateLong(object time)
        {
            DateTime epoc = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            TimeSpan delta = new TimeSpan();

            if (time is DateTime)
                delta = ((DateTime)time).Subtract(epoc);

            else if (time is string)
                delta = DateTime.Parse(time.ToString()).Subtract(epoc);

            else
                throw new ArgumentOutOfRangeException("時間格式錯誤.1");

            if (delta.TotalMilliseconds < 0)
                throw new ArgumentOutOfRangeException("時間格式錯誤.2");

            long ticks = (long)delta.TotalMilliseconds;
            return ticks;
        }

long轉DateTime:

public static DateTime GetDateFromLong(long ticks)
        {
            var date = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            date = date.AddMilliseconds(ticks);
            return date;
        }

網上常見錯誤:

DateTime epoc = new DateTime(1970, 1, 1);

 


免責聲明!

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



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