C# 时间戳和日期相互转换


1.日期转换为时间戳Timestamp

        /// <summary>
        /// 日期转换为时间戳Timestamp
        /// </summary>
        /// <param name="dateTime">要转换的日期</param>
        /// <returns></returns>
        public static long GetTimeStamp(DateTime dateTime)
        {
            DateTime _dtStart = new DateTime(1970, 1, 1, 8, 0, 0);
            //10位的时间戳
            long timeStamp = Convert.ToInt32(dateTime.Subtract(_dtStart).TotalSeconds);
            //13位的时间戳
            //long timeStamp = Convert.ToInt64(dateTime.Subtract(_dtStart).TotalMilliseconds);
            return timeStamp;
        }

2.时间戳转换为时间

        /// <summary>
        /// UTC时间戳Timestamp转换为北京时间
        /// </summary>
        /// <param name="timestamp">要转换的时间戳</param>
        /// <returns></returns>
        public static DateTime GetDateTime(long timestamp)
        {
            //DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); 
            //使用上面的方式会显示TimeZone已过时
            DateTime dtStart = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);
            long lTime = long.Parse(timestamp + "0000000");
            TimeSpan timeSpan = new TimeSpan(lTime);
            DateTime targetDt = dtStart.Add(timeSpan).AddHours(8);
            return targetDt;
        }

3.日期转换公共类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WeChatDemo.Common
{
    public class DateTimeHelper
    {
        /// <summary>
        /// 日期转换为时间戳Timestamp
        /// </summary>
        /// <param name="dateTime">要转换的日期</param>
        /// <returns></returns>
        public static long GetTimeStamp(DateTime dateTime)
        {
            DateTime _dtStart = new DateTime(1970, 1, 1, 8, 0, 0);
            //10位的时间戳
            long timeStamp = Convert.ToInt32(dateTime.Subtract(_dtStart).TotalSeconds);
            //13位的时间戳
            //long timeStamp = Convert.ToInt64(dateTime.Subtract(_dtStart).TotalMilliseconds);
            return timeStamp;
        }

        /// <summary>
        /// UTC时间戳Timestamp转换为北京时间
        /// </summary>
        /// <param name="timestamp">要转换的时间戳</param>
        /// <returns></returns>
        public static DateTime GetDateTime(long timestamp)
        {
            //DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); 
            //使用上面的方式会显示TimeZone已过时
            DateTime dtStart = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);
            long lTime = long.Parse(timestamp + "0000000");
            TimeSpan timeSpan = new TimeSpan(lTime);
            DateTime targetDt = dtStart.Add(timeSpan).AddHours(8);
            return targetDt;
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM