Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go时间日期实例
Go时间日期实例
作者:--    发布时间:2019-11-20

go编程为时间和持续时间提供广泛的支持; 这里有些例子。我们将从获取当前时间开始。也可以通过提供年,月,日等来构建时间结构。时间总是与位置(即时区)相关联。

具体的每个函数,可参考示例中的代码 -

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html

json.go的完整代码如下所示 -

package main

import "fmt"
import "time"

func main() {
    p := fmt.println

    // we'll start by getting the current time.
    now := time.now()
    p(now)

    // you can build a `time` struct by providing the
    // year, month, day, etc. times are always associated
    // with a `location`, i.e. time zone.
    then := time.date(
        2009, 11, 17, 20, 34, 58, 651387237, time.utc)
    p(then)

    // you can extract the various components of the time
    // value as expected.
    p(then.year())
    p(then.month())
    p(then.day())
    p(then.hour())
    p(then.minute())
    p(then.second())
    p(then.nanosecond())
    p(then.location())

    // the monday-sunday `weekday` is also available.
    p(then.weekday())

    // these methods compare two times, testing if the
    // first occurs before, after, or at the same time
    // as the second, respectively.
    p(then.before(now))
    p(then.after(now))
    p(then.equal(now))

    // the `sub` methods returns a `duration` representing
    // the interval between two times.
    diff := now.sub(then)
    p(diff)

    // we can compute the length of the duration in
    // various units.
    p(diff.hours())
    p(diff.minutes())
    p(diff.seconds())
    p(diff.nanoseconds())

    // you can use `add` to advance a time by a given
    // duration, or with a `-` to move backwards by a
    // duration.
    p(then.add(diff))
    p(then.add(-diff))
}

执行上面代码,将得到以下输出结果 -

f:\worksp\golang>go run time.go
2017-01-21 16:59:10.8307711 +0800 cst
2009-11-17 20:34:58.651387237 +0000 utc
2009
november
17
20
34
58
651387237
utc
tuesday
true
false
false
62916h24m12.179383863s
62916.403383162185
3.774984202989731e+06
2.2649905217938387e+08
226499052179383863
2017-01-21 08:59:10.8307711 +0000 utc
2002-09-14 08:10:46.472003374 +0000 utc

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册