71 lines
2.8 KiB
C#
71 lines
2.8 KiB
C#
|
|
using System;
|
|||
|
|
using System.Collections.Generic;
|
|||
|
|
using System.Linq;
|
|||
|
|
using System.Text;
|
|||
|
|
|
|||
|
|
namespace Common
|
|||
|
|
{
|
|||
|
|
public static class TimeHelper
|
|||
|
|
{
|
|||
|
|
/// <summary>
|
|||
|
|
/// 时间转unix时间戳
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="now"></param>
|
|||
|
|
/// <returns></returns>
|
|||
|
|
public static long DateTimeToStamp(DateTime now)
|
|||
|
|
{
|
|||
|
|
return (now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
|
|||
|
|
}
|
|||
|
|
/// <summary>
|
|||
|
|
/// 获取当前时间戳
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="millisecond">精度(毫秒)设置 true,则生成13位的时间戳;精度(秒)设置为 false,则生成10位的时间戳;默认为 true </param>
|
|||
|
|
/// <returns></returns>
|
|||
|
|
public static string GetCurrentTimestamp(bool millisecond = true)
|
|||
|
|
{
|
|||
|
|
return DateTime.Now.ToTimestamp(millisecond);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 转换指定时间得到对应的时间戳
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="dateTime"></param>
|
|||
|
|
/// <param name="millisecond">精度(毫秒)设置 true,则生成13位的时间戳;精度(秒)设置为 false,则生成10位的时间戳;默认为 true </param>
|
|||
|
|
/// <returns>返回对应的时间戳</returns>
|
|||
|
|
public static string ToTimestamp(this DateTime dateTime, bool millisecond = true)
|
|||
|
|
{
|
|||
|
|
return dateTime.ToTimestampLong(millisecond).ToString();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 转换指定时间得到对应的时间戳
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="dateTime"></param>
|
|||
|
|
/// <param name="millisecond">精度(毫秒)设置 true,则生成13位的时间戳;精度(秒)设置为 false,则生成10位的时间戳;默认为 true </param>
|
|||
|
|
/// <returns>返回对应的时间戳</returns>
|
|||
|
|
public static long ToTimestampLong(this DateTime dateTime, bool millisecond = true)
|
|||
|
|
{
|
|||
|
|
var ts = dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0);
|
|||
|
|
return millisecond ? Convert.ToInt64(ts.TotalMilliseconds) : Convert.ToInt64(ts.TotalSeconds);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 转换指定时间戳到对应的时间(同时增加八个小时)
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="timestamp">(10位或13位)时间戳</param>
|
|||
|
|
/// <returns>返回对应的时间</returns>
|
|||
|
|
public static DateTime ToDateTime(this long timestamp)
|
|||
|
|
{
|
|||
|
|
var tz = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0, 0));
|
|||
|
|
if (timestamp.ToString().Length == 13)
|
|||
|
|
{
|
|||
|
|
return tz.AddMilliseconds(Convert.ToInt64(timestamp));
|
|||
|
|
}
|
|||
|
|
else
|
|||
|
|
{
|
|||
|
|
return tz.AddSeconds(Convert.ToInt64(timestamp));
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|