如何获取两个日期之间的小时差异

huangapple go评论85阅读模式
英文:

How to get hours difference between two dates

问题

我第一次在Go上工作,这种情况下我有一个以UTC格式表示的字符串,我想知道如何计算我的日期和当前时间之间的小时差。这是我的当前字符串:

v := "2014-05-03 20:57 UTC"
英文:

I'm working for first time on Go, in this case i have a string on UTC format, I would like to know, how can I get the difference in hours between my date and the time now.
This is my current string

v := "2014-05-03 20:57 UTC"

答案1

得分: 85

使用time.Parsetime.Since函数进行时间解析和计算时间间隔:

package main

import (
	"fmt"
	"time"
)

const (
	// 参考 http://golang.org/pkg/time/#Parse
	timeFormat = "2006-01-02 15:04 MST"
)

func main() {
	v := "2014-05-03 20:57 UTC"
	then, err := time.Parse(timeFormat, v)
	if err != nil {
		fmt.Println(err)
		return
	}
	duration := time.Since(then)
	fmt.Println(duration.Hours())
}
英文:

Use time.Parse and time.Since:

package main

import (
	"fmt"
	"time"
)

const (
	// See http://golang.org/pkg/time/#Parse
	timeFormat = "2006-01-02 15:04 MST"
)

func main() {
	v := "2014-05-03 20:57 UTC"
	then, err := time.Parse(timeFormat, v)
	if err != nil {
		fmt.Println(err)
        return
	}
	duration := time.Since(then)
	fmt.Println(duration.Hours())
}

答案2

得分: 43

请看一下time包

package main

import "fmt"
import "time"

func main() {
	a, err := time.Parse("2006-01-02 15:04 MST", "2014-05-03 20:57 UTC")
	if err != nil {
		// ...
		return
	}

	delta := time.Now().Sub(a)
	fmt.Println(delta.Hours())
}
英文:

Have a look at the time package.

package main

import "fmt"
import "time"

func main() {
	a, err := time.Parse("2006-01-02 15:04 MST", "2014-05-03 20:57 UTC")
	if err != nil {
		// ...
		return
	}

	delta := time.Now().Sub(a)
	fmt.Println(delta.Hours())
}

huangapple
  • 本文由 发表于 2014年5月24日 05:55:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/23838857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定