c#日期和时间戳互转

using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace Common
{
    public static class ExtendMethod
    {
        // DateTime --> long
        public static long? ConvertDataTimeToLong(this DateTime? dt)
        {
            if (dt == null || dt == default(DateTime)) return null;
            try
            {
                DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
                TimeSpan toNow = dt.Value.Subtract(dtStart);
                long timeStamp = toNow.Ticks;
                timeStamp = long.Parse(timeStamp.ToString().Substring(0, timeStamp.ToString().Length - 4));
                return timeStamp <= 0 ? 0 : timeStamp;
            }
            catch
            {
                return null;
            }
        }

        // long --> DateTime
        public static DateTime? ConvertLongToDateTime(this long? d)
        {
            if (d == 0) return null;
            try
            {
                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;
            }
            catch
            {
                return null;
            }
        }
    }
}

 

posted @ 2018-06-29 10:20  潇潇与偕  阅读(474)  评论(0编辑  收藏  举报