douzong5057
2015-10-15 09:37 阅读 46

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

I have the following code which takes a string as input which is converted into UNIX time stamp. I want to do the same in golang but I am not able to recognize the struct or function which will give an equivalent of DateTimeOffset structure in Go.

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

For example:

Input: 635804753769100000

Output: 1444878577

Corresponding Time in UTC : 10/15/2015 3:09:36 AM +00:00

Can someone please help me on a workaround to get the above result.

Thanks

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dsz1966 dsz1966 2015-10-16 02:43

    For example,

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

    Output:

    2015-10-15 03:09:36.0091 +0000 UTC
    
    点赞 评论 复制链接分享
  • douwen3836 douwen3836 2015-10-15 09:52

    I believe the time package has everything you need and it is IMO the best time library I've worked with in any language. Example:

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

    EDIT Converting the time object back to a unix timestamp is simple:

    t.Unix()
    

    or

    t.UnixNano()
    
    点赞 评论 复制链接分享

相关推荐