using System;

namespace Server
{
    public class DateTimeHelper
    {
        private static readonly System.DateTime unixTime =
            TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));

        /// <summary>
        /// 时间转时间戳
        /// </summary>
        /// <param name="time">时间</param>
        /// <param name="bflag">true 表示10位时间戳 false 表示13位时间戳</param>
        /// <returns>时间戳</returns>
        public static long DateTime2TimeStamp(System.DateTime time, bool bflag = true)
        {
            TimeSpan ts = time - unixTime;
            if (bflag)
                return Convert.ToInt64(ts.TotalSeconds);
            else
                return Convert.ToInt64(ts.TotalMilliseconds);
        }
            
        /// <summary>
        /// 时间戳转时间
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <returns></returns>
        public static System.DateTime TimeStamp2DateTime(long timeStamp)
        {
            string timeStampStr = timeStamp.ToString();
            if (timeStampStr.Length == 10)
            {
                DateTimeOffset dateTime = DateTimeOffset.FromUnixTimeSeconds(timeStamp);
                dateTime = dateTime.ToOffset(TimeSpan.FromHours(8)); //UTC 转北京时间
                return dateTime.DateTime;
            }

            if (timeStampStr.Length == 13)
            {
                DateTimeOffset dateTime = DateTimeOffset.FromUnixTimeMilliseconds(timeStamp);
                dateTime = dateTime.ToOffset(TimeSpan.FromHours(8));
                return dateTime.DateTime;
            }

            return System.DateTime.MinValue;
        }

        public static float TimeBeTween(System.DateTime now,System.DateTime last)
        {
            TimeSpan ts = now.Subtract(last).Duration();

            return (float)ts.TotalMilliseconds;
        }
    }
}