【问题标题】:How to Convert Timestamp to DateTime?如何将时间戳转换为日期时间?
【发布时间】:2019-04-03 07:08:44
【问题描述】:

我想将纪元转换为人类可读的日期,反之亦然。
我想用 C# 写类似link 的东西。

将 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 不够,我尝试了很长的 epoch 但不起作用

【问题讨论】:

标签: c# firefox timestamp epoch


【解决方案1】:

您的时间是以微秒为单位的 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)

【讨论】:

  • 谢谢老哥 time/1000 因为毫秒
  • 你是家人吗?谁知道你的名字...@ThanawutPadermwong
  • 谁知道你的名字。对不起,我不明白
【解决方案2】:

时间戳是从 1970 年 1 月 1 日开始的秒数

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

【讨论】:

    【解决方案3】:

    这个例子我修好了

        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(); }
    

    【讨论】:

    • 请编辑您的问题,而不是发布更新作为答案。我现在已经为你完成了。
    猜你喜欢
    • 1970-01-01
    • 2017-04-25
    • 2022-01-08
    • 1970-01-01
    • 2020-10-19
    • 2016-11-26
    相关资源
    最近更新 更多