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

Sre*_*ree 3 c#

以下是在C#中将java datetamp(13位数字)转换为date(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");
Run Code Online (Sandbox Code Playgroud)

我需要反转此功能,需要从转换3/12/2018 8:07:02 PM1520488577604

Pau*_*her 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它

using MyApp.Extensions;

// ...
var millisecondsTimestamp = DateTime.Now.MillisecondsTimestamp();
Run Code Online (Sandbox Code Playgroud)

假设您已添加所在的名称空间DateTimeExtensions