将当前日期和时间转换为时间戳对象(13位数)

时间:2018-03-13 05:22:21

标签: c#

以下是在C#中将java datestamp(13digits)转换为日期(15204885776043/12/2018 8:07:02 PM)的代码。

new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
    .AddMilliseconds((long)value) // put your value here
    .ToLocalTime().ToString("g");

我需要撤销此功能,需要从3/12/2018 8:07:02 PM转换为1520488577604

3 个答案:

答案 0 :(得分:5)

虽然Gavin和Gaurang非常接近,但他们错过了一个细节:你想要从1970/01/01开始的总毫秒

namespace MyApp.Extensions
{
    public static class DateTimeExtensions
    {
        public static long MillisecondsTimestamp(this DateTime date)
        {
            DateTime baseDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return (long)(date.ToUniversalTime()-baseDate).TotalMilliseconds;
        }
    }
}

您可以像

一样使用它
using MyApp.Extensions;

// ...
var millisecondsTimestamp = DateTime.Now.MillisecondsTimestamp();

鉴于您已添加DateTimeExtensions所在的命名空间。

答案 1 :(得分:1)

试试这个:

10位数:

public static long ConvertToTS(DateTime datetime)
{
    DateTime sTime = new DateTime(1970, 1, 1,0,0,0,DateTimeKind.Utc);

    return (long)(datetime - sTime).TotalSeconds;
}

13位数:

public static long ConvertToTS(DateTime datetime)
{
    DateTime sTime = new DateTime(1970, 1, 1,0,0,0,DateTimeKind.Utc);

    return (long)(datetime - sTime).TotalMilliseconds;
}

答案 2 :(得分:1)

Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

How to get the unix timestamp in C#