小编典典

Go中的C#DateTimeOffset等效项是什么

go

我有以下代码,该代码将字符串作为输入,并转换为UNIX时间戳。我想在golang中做同样的事情,但我无法识别将在Go中提供等效于DateTimeOffset结构的结构或函数。

class Program
{
    static void Main(string[] args)
    {
        var date = GetUtcTimestampFromAttribute();
        Console.WriteLine(date);
        if (date != null)
        {
            Console.WriteLine(ToUnixTimeStamp(date.Value));
        }

        Console.ReadKey();
    }

    public static DateTimeOffset? GetUtcTimestampFromAttribute()
    {
        var ticks = long.Parse("7036640000000");
        Console.WriteLine(ticks);
        return GetUtcTimestampFromTicks(ticks);
    }

    public static DateTimeOffset? GetUtcTimestampFromTicks(long ticks)
    {
        Console.WriteLine(new DateTimeOffset(ticks, TimeSpan.Zero));
        return ticks != 0 ?
            new DateTimeOffset(ticks, TimeSpan.Zero) :
            (DateTimeOffset?)null;
    }

    public static long ToUnixTimeStamp(DateTimeOffset timeStamp)
    {
        var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
        return Convert.ToInt64((timeStamp - epoch).TotalSeconds);
    }
}

例如:

输入:635804753769100000

输出:1444878577

UTC对应时间:10/15/2015 3:09:36 AM +00:00

有人可以帮我解决这个问题,以获得上述结果。

谢谢


阅读 259

收藏
2020-07-02

共1个答案

小编典典

例如,

package main

import (
    "fmt"
    "time"
)

func TimeFromTicks(ticks int64) time.Time {
    base := time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix()
    return time.Unix(ticks/10000000+base, ticks%10000000).UTC()
}

func main() {
    fmt.Println(TimeFromTicks(635804753769100000))
}

输出:

2015-10-15 03:09:36.0091 +0000 UTC
2020-07-02