繁体   English   中英

如何将时间戳转换为日期时间?

[英]How to Convert Timestamp to DateTime?

我想将纪元转换为人类可读的日期,反之亦然。
我想写一些类似于 C# 中的链接的东西。

将 Firefox 中 Places.sqlite 文件中的日期转换为 DateTime。

static void Main(string[] args)
{
    //1540787809621000
    string epoch = "1540787809621000";
}

private string epoch2string(int epoch) {
    return 
        new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
            .AddSeconds(epoch)
            .ToShortDateString(); 
}

int size 不够,我尝试了 long epoch 但没有用

您的时间是以微秒为单位的 Unix 时间。

如果您使用 .Net 4.6 或更高版本,您可以将其转换为DateTime ,如下所示。

long time = 1540787809621000; // Unix time in microseconds.

time /= 1000; // Divide by 1,000 because we need milliseconds, not microseconds.

DateTime result = DateTimeOffset.FromUnixTimeMilliseconds(time).DateTime;

Console.WriteLine(result); // Prints 29/10/2018 04:36:49 (UK format)

时间戳是从 1/1/1970 开始的秒数

static DateTime ConvertFromUnixTimestamp(double timestamp)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return origin.AddSeconds(timestamp);
}

这个例子我修复了它

    static void Main(string[] args)
    {
        //1540787809621000
        int epoch = "1540787809621000"; //this microseconds 
        epoch /= 1000; // convert to milliseconds by divide 1000  
        epoch2string(epoch) 
    }

private string epoch2string(int epoch) {
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epoch).ToShortDateString(); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM