美文网首页
DateTime 转换工具类

DateTime 转换工具类

作者: 忆中异 | 来源:发表于2021-04-20 12:16 被阅读0次

1.时间戳转DateTime格式
2.DateTime时间格式转换为Unix时间戳格式
3.客户端服务器时间校准差值
4.切分时间,输出对应年月日时分秒星期 返回DataTime
5.格式化为xx分xx秒
6.格式化位xx天xx时xx分xx秒
7.时间秒数转换成XX:XX:XX格式

TimeUtils.cs代码如下:

using System;
using UnityEngine;
using System.Text;

public class TimeUtils 
{
    /* 客户端服务器时间校准差值 */
    public static double timeAdjustValue = 0;
    public static DateTime dt1 = DateTime.Parse("1970-1-1 8:0:0");


    /// <summary>
    /// 时间戳转为C#格式时间
    /// </summary>
    /// <param name=”timeStamp”></param>
    /// <returns></returns>
    public static DateTime GetTime(string timeStamp)
    {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(timeStamp + "0000000");
        TimeSpan toNow = new TimeSpan(lTime); 
        return dtStart.Add(toNow);
    }

    public static DateTime GetDateTime(long second)
    {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
     
        return dtStart.AddSeconds(second);
    }
    public static DateTime GetUtcTime(long utcSecond)
    {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToUniversalTime(new DateTime(1970, 1, 1) + TimeZoneInfo.Local.BaseUtcOffset);

        return dtStart.AddSeconds(utcSecond);
    }

    /// <summary>
    /// DateTime时间格式转换为Unix时间戳格式
    /// </summary>
    /// <param name=”time”></param>
    /// <returns></returns>
    public static string ConvertDateTime(System.DateTime time)
    {
        //datetime计算时有时区缓存
        //TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)),东八区输出时间为1970/1/1 8:00:00
        //TimeZone.CurrentTimeZone.ToUniversalTime(new System.DateTime(1970, 1, 1)) ,东八区输出时间为1969/12/31 16:00:00
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        return Convert.ToString((int)(time - startTime).TotalSeconds);
    }
    public static long ConvertLongDateTime(System.DateTime time)
    {
        string str = ConvertDateTime(time);
        return long.Parse(str);
    }

  //  public static string ConvertDateTime(System.DateTime time)
  //  {
        //DateTime time1 =  GetDateTime(1619072942);
        //DateTime time2 = GetUtcTime(1619072942);
        //Debug.Log($"time1={time1},time2={time2}");


        //TimeZoneInfo.ClearCachedData();
  //      System.DateTime startTime = TimeZone.CurrentTimeZone.ToUniversalTime(new System.DateTime(1970, 1, 1) + TimeZoneInfo.Local.BaseUtcOffset);
  //      System.DateTime start = TimeZoneInfo.ConvertTimeToUtc(new System.DateTime(1970, 1, 1));
  //      System.DateTime start1 = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
  //      int a = (int)(time - startTime).TotalSeconds;
  //      int b = (int)(DateTime.Now - startTime).TotalSeconds;
  //      int c = (int)(DateTime.UtcNow - startTime).TotalSeconds;
  //      int aa = (int)(time - start).TotalSeconds;
  //      int bb = (int)(DateTime.Now - start).TotalSeconds;
  //      int cc = (int)(DateTime.UtcNow - start).TotalSeconds;
  //      int aaa = (int)(time - start1).TotalSeconds;
  //      DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  //      dtStart = dtStart.AddSeconds((double)aaa);
  //      Debug.Log($"dtStart={dtStart}");
  //      int aaaa = (int)(time - new System.DateTime(1970, 1, 1)).TotalSeconds;
  //      Debug.Log($"1970={new System.DateTime(1970, 1, 1)}");
  //      Debug.Log($"1970 offset={new System.DateTime(1970, 1, 1) + TimeZoneInfo.Local.BaseUtcOffset }");
  //      Debug.Log($"utc={TimeZone.CurrentTimeZone.ToUniversalTime(time)}");
  //      DateTime now = DateTime.Now;
  //      Debug.Log($"utc11={TimeZone.CurrentTimeZone.ToUniversalTime(now)},now={DateTime.Now}");
  //      Debug.Log($"time={time},startTime={startTime},start={start},start1={start1},a={a},b={b},c={c},aa={aa},bb={bb},cc={cc},aaa={aaa},aaaa={aaaa}");
  //      return Convert.ToString((int)(time - startTime).TotalSeconds);
  //  }
  //  public static long ConvertLongDateTime(System.DateTime time)
  //  {
  //      string str = ConvertDateTime(time);
  //      return long.Parse(str);
  //  }
    /// <summary>
    /// Adjusts the time value.
    /// 客户端服务器时间校准差值
    /// </summary>
    /// <param name="serverMilliseconds">Server milliseconds.</param>
    public static void AdjustTimeValue(long serverMilliseconds)
    {
        double clientMilliseconds = System.DateTime.Now.Subtract(System.DateTime.Parse("1970-1-1 8:0:0")).TotalMilliseconds;
        timeAdjustValue = serverMilliseconds - clientMilliseconds;
    }

    public static long getNowTicket ( ) {
        DateTime dt2 = DateTime.Parse(DateTime.Now.AddMilliseconds(timeAdjustValue).ToString());
        TimeSpan ts = dt2 - dt1;
        long ds = ts.Ticks / 10000000;
        return ds;
    }

    public static long getNowTicketMs ( ) {
        timeAdjustValue = 0;
        DateTime dt2 = DateTime.Parse(DateTime.Now.AddMilliseconds(timeAdjustValue).ToString());
        TimeSpan ts = dt2 - dt1;
        long ds = ts.Ticks  / 10000 + DateTime.Now.Millisecond;
        return ds;
    }   

    public static string ToString (int ticket) {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(ticket + "0000000");
        TimeSpan toNow = new TimeSpan(lTime);
        DateTime dtResult = dtStart.Add(toNow);
        return dtResult.ToString("yyyy-MM-dd HH:mm");
    }

    public static string toStringMMdd (int ticket) {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(ticket + "0000000");
        TimeSpan toNow = new TimeSpan(lTime);
        DateTime dtResult = dtStart.Add(toNow);
        return dtResult.ToString("MM/dd");
    }

    public static string toStringHHmm (int ticket) {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(ticket + "0000000");
        TimeSpan toNow = new TimeSpan(lTime);
        DateTime dtResult = dtStart.Add(toNow);
        return dtResult.ToString("HH:mm");
    }

    public static string getDateFormat (int ticket) {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(ticket + "0000000");
        TimeSpan toNow = new TimeSpan(lTime);
        DateTime dtResult = dtStart.Add(toNow);
        return dtResult.Month + "月" + dtResult.Day + "日";
    }



    #region 切分时间,输出对应年月日时分秒星期 返回DataTime

    /// <summary>
    /// Split the specified ticket, yr, mm, dd, hh, ms, ss and dayofweek.
    /// 切分时间,输出对应年月日时分秒星期
    /// </summary>
    /// <param name="ticket">Ticket.</param>
    /// <param name="yr">Yr.</param>
    /// <param name="mm">Mm.</param>
    /// <param name="dd">Dd.</param>
    /// <param name="hh">Hh.</param>
    /// <param name="ms">Ms.</param>
    /// <param name="ss">Ss.</param>
    /// <param name="dayofweek">Dayofweek.</param>
    public static DateTime split(uint ticket, out int yr, out int mm, out int dd, out int hh, out int ms, out int ss, out int dayofweek) {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(ticket + "0000000");
        TimeSpan toNow = new TimeSpan(lTime);
        DateTime dtResult = dtStart.Add(toNow);
        yr = dtResult.Year;
        mm = dtResult.Month;
        dd = dtResult.Day;
        hh = dtResult.Hour;
        ms = dtResult.Minute;
        ss = dtResult.Second;
        dayofweek = (int) dtResult.DayOfWeek;
        if (dayofweek == 0)
            dayofweek = 7;
        return dtResult;
    }

    #endregion

    #region 格式化为xx分xx秒

    /// <summary>
    /// Secondses to string.
    /// 格式化为 xx : xx
    /// </summary>
    /// <returns>The to string.</returns>
    /// <param name="seconds">Seconds.</param>
    public static string secondsToString (int seconds) {
        int minute = Mathf.CeilToInt(seconds / 60);
        int second = Mathf.CeilToInt(seconds - minute * 60);

        string min_str = string.Format("{0:00}", minute);
        string second_str = string.Format("{0:00}", second);
        return min_str + ":" + second_str;
    }

    #endregion
    /// <summary>
    /// 格式化为xx分xx秒
    /// </summary>
    /// <param name="seconds"></param>
    /// <returns></returns>
    public static string secondsToString1(int seconds)
    {
        int minute = Mathf.CeilToInt(seconds / 60);
        int second = Mathf.CeilToInt(seconds - minute * 60);

        string min_str = string.Format("{0:00}", minute);
        string second_str = string.Format("{0:00}", second);
        return min_str + "分" + second_str + "秒";
    }

    #region 格式化位xx天xx时xx分xx秒

    /// <summary>
    /// Secondses to string4.
    /// 格式化为xx天xx时xx分xx秒
    /// </summary>
    /// <returns>The to string4.</returns>
    /// <param name="seconds">Seconds.</param>
    public static string secondsToString4(int seconds)
    {
        StringBuilder buffer = new StringBuilder ();

        int day = seconds / (24 * 3600);
        int hour = Mathf.CeilToInt((seconds % (24 * 3600)) / 3600);
        int minute = Mathf.CeilToInt( (seconds % (24 * 3600)) % 3600 / 60);
        int second = Mathf.CeilToInt( (seconds % (24 * 3600)) % 3600 % 60);
        if(day>0){
            buffer.Append (day.ToString ());
            buffer.Append ("天");
        }

        if(0 <= hour  && hour  <= 9){
            buffer.Append("0");
        }
        buffer.Append(hour.ToString());
        buffer.Append("时");

        if(0 <= minute  && minute  <= 9){
            buffer.Append("0");
        }
        buffer.Append(minute.ToString());
        buffer.Append("分");

        if(0 <= second  && second  <= 9){
            buffer.Append("0");
        }
        buffer.Append(second.ToString());
        buffer.Append("秒");

        string timeText = buffer.ToString ();
        buffer.Remove (0, buffer.Length);

        return timeText;
    }

    #endregion

    /// <summary>
    /// Secondses to string3.
    /// </summary>
    /// <returns>The to string3.</returns>
    /// <param name="seconds">Seconds.</param>
    public static string secondsToString3 (int seconds) {
        
        if (seconds < 60)
        {
            string second_str = string.Format("{0:00}", seconds);
            return second_str + "秒";
        }
        else if (seconds < 3600)
        {
            int minute = Mathf.CeilToInt(seconds / 60);
            //int second = Mathf.CeilToInt(seconds - minute * 60);

            string min_str = string.Format("{0:00}", minute);
            //string second_str = string.Format("{0:00}", second);
            return min_str + "分";
        }
        else if (seconds < 24 * 3600)
        {
            int hour = Mathf.CeilToInt(seconds / 3600);
            //int minute = Mathf.CeilToInt( seconds % 3600 / 60);
            //int second = Mathf.CeilToInt( seconds % 3600 % 60);

            string shour = "";
            //string sminute = "";
            //string ssecond = "";

            if(0 <= hour  && hour  <= 9)
                shour = "0" + hour;
            else
                shour = hour.ToString();
            //if(0 <= minute && minute  <= 9)
            //  sminute = "0" + minute;
            //else
            //  sminute = minute.ToString();
            //if(0 <= second && second  <= 9)
            //  ssecond = "0" + second;
            //else
            //  ssecond = second.ToString();

            return shour + "时";
        }
        else
        {
            int day = seconds / (24 * 3600);
            return day * 24 + "天";
        }
    }

    #region 时间秒数转换成XX:XX:XX格式

    /// <summary>
    /// Secondses to string2.
    /// 时间秒数转换成XX:XX:XX格式
    /// 倒计时或者计时使用
    /// </summary>
    /// <returns>The to string2.</returns>
    /// <param name="seconds">Seconds.</param>
    public static string secondsToString2(int seconds)
    {
        int hour = Mathf.CeilToInt(seconds / 3600);
        int minute = Mathf.CeilToInt( seconds % 3600 / 60);
        int second = Mathf.CeilToInt( seconds % 3600 % 60);

        string shour = "";
        string sminute = "";
        string ssecond = "";

        if(0 <= hour  && hour  <= 9)
            shour = "0" + hour;
        else
            shour = hour.ToString();
        if(0 <= minute && minute  <= 9)
            sminute = "0" + minute;
        else
            sminute = minute.ToString();
        if(0 <= second && second  <= 9)
            ssecond = "0" + second;
        else
            ssecond = second.ToString();

        return shour + ":" + sminute + ":" + ssecond;
    }
    #endregion

    #region 登陆时间判断
    /// <summary>
    /// Secondses to tips.
    /// 是否在线,登陆时间
    /// 离线
    /// xx年前
    /// xx个月前
    /// xx天前
    /// xx小时前
    /// xx分钟前
    /// 刚刚
    /// </summary>
    /// <returns>The to tips.</returns>
    /// <param name="seconds">Seconds.</param>
    public static string secondsToTips (int seconds)
    {
        int YEAR = 365*24*60*60;
        int MONTH = 30*24*60*60;
        int DAY = 24*60*60;
        int HOUR = 60*60;
        int MINUTE = 60;
        long timeGap = getNowTicket()-seconds;
        string timeStr="";
        if(seconds == 0)
        {
            timeStr = "离线";
        }
        else if(timeGap>YEAR)
        {
            timeStr = timeGap/YEAR + "年前";
        } else if(timeGap>MONTH)
        {
            timeStr = timeGap/MONTH + "个月前";
        } else if(timeGap>DAY)
        {
            timeStr = timeGap/DAY + "天前";
        } else if(timeGap>HOUR)
        {
            timeStr = timeGap/HOUR + "小时前";
        } else if(timeGap>MINUTE)
        {
            timeStr = timeGap/MINUTE + "分钟前";
        } else
        {
            timeStr = "刚刚";
        }
        return timeStr;
    }
    #endregion
}



以下代码为计算当前时区的时间戳,比如:东八区TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))计算结果为1970/1/1 08:00:00

DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
return Convert.ToString((int)(time - startTime).TotalSeconds);

当你为DateTime转换时间戳成功庆幸的时候,却不知埋下了时间戳验证不通过的祸根。因为当时区切换的时候,存在着时区缓存。

经过微软对 TimeZone.CurrentTimeZone 的描述中有这样一段话: Local time zone data is cached after CurrentTimeZone is first used to retrieve time zone information. If the system’s local time zone subsequently changes, the CurrentTimeZone property does not reflect this change. If you need to handle time zone changes while your application is running, use the TimeZoneInfo class and call its ClearCachedData() method. 看了这段话,便写了 demo 去验证,结果得到了同样的错误结果。

奇怪,明明清理了时区缓存,为什么还是一样的结果(这里的原因暂时未知,还请知道的大佬指导一下)。为了解决这个奇怪的现象,继续查看官方文档 TimeZone.CurrentTimeZone 发现了这样一段话:The CurrentTimeZone property corresponds to the TimeZoneInfo.Local property. Whenever possible, use the TimeZoneInfo.Local property. 按照建议,写了另外一个 demo 。

这时候的输出就是日思夜想的结果。于是把计算UTC时间戳的代码更改为

TimeZoneInfo.ClearCachedData();
var startTime = new DateTime(1970, 1, 1) + TimeZoneInfo.Local.BaseUtcOffset;
var timeStamp = (long)(DateTime.Now - startTime).TotalSeconds;

至此,问题得到解决。

结论
尽量使用 TimeZoneInfo.Local 替换 TimeZone.CurrentTimeZone
如果时区切换会影响到你程序的功能,使用 TimeZoneInfo.ClearCachedData() 清除时区缓存。

相关文章

网友评论

      本文标题:DateTime 转换工具类

      本文链接:https://www.haomeiwen.com/subject/lixnlltx.html