c# - Go 中的 C# DateTimeOffset 等价物是什么

标签 c# datetime 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

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

谢谢

最佳答案

我相信 time 包拥有您需要的一切,在我看来,它是我用过的任何语言中最好的时间库。示例:

package main 

import(
    "fmt"
    "time"
)

func main(){

    // this is how you parse a unix timestamp    
    t := time.Unix(1444902545, 0)

    // get the UTC time
    fmt.Println("The time converted to UTC:", t.UTC())

    // convert it to any zone: FixedZone can take a utc offset and zone name
    fmt.Println(t.In(time.FixedZone("IST", 7200)))

}

编辑将时间对象转换回 unix 时间戳很简单:

t.Unix()

t.UnixNano()

关于c# - Go 中的 C# DateTimeOffset 等价物是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33144967/

相关文章:

python - 使用 matplotlib 更改 python 条形图中日期时间数据的 x 轴刻度标签的频率

sql - 在 SQL Server 中将年份 (aaaa) 和季度(1 到 4)转换为日期时间

go - 如何并行化递归函数

mysql - golang sql driver的prepare语句

json - 在 GO 中发送 POST 请求时收到错误响应 - 来自服务器的 422

c# - 如何从 json 序列化 protobuf,并自动忽略 C# 中的未知字段?

c# - Entity Framework 和默认值

javascript - ASP.NET 中的 Google map 无法加载

c# - 简化LINQ-使用两个不同的where子句的Col的总和两次

json - 在Hive中将时间戳转换为Hive格式时出错