首页 > 后端开发 > Golang > 正文

出发时间和持续时间|编程教程

王林
发布: 2024-09-12 10:16:35
原创
729 人浏览过

介绍

Go Time and Duration | Programming Tutorials

本实验旨在测试您对 Go 的时间和持续时间支持的理解。

时间

下面的代码包含如何在 Go 中使用时间和持续时间的示例。但是,代码的某些部分丢失了。您的任务是完成代码,使其按预期工作。

  • Go 编程语言的基础知识。
  • 熟悉 Go 的时间和持续时间支持。
$ go run time.go
2012-10-31 15:50:13.793654 +0000 UTC
2009-11-17 20:34:58.651387237 +0000 UTC
2009
November
17
20
34
58
651387237
UTC
Tuesday
true
false
false
25891h15m15.142266763s
25891.25420618521
1.5534752523711128e+06
9.320851514226677e+07
93208515142266763
2012-10-31 15:50:13.793654 +0000 UTC
2006-12-05 01:19:43.509120474 +0000 UTC

# Next we'll look at the related idea of time relative to
# the Unix epoch.
登录后复制

完整代码如下:

// Go offers extensive support for times and durations;
// here are some examples.

package main

import (
    "fmt"
    "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))
}

登录后复制

概括

本实验室测试了您使用 Go 的时间和持续时间支持的能力。您学习了如何提取时间值的各个组成部分、比较两次、计算持续时间的长度以及将时间提前给定的持续时间。


?立即练习:探索时间和持续时间


想了解更多吗?

  • ?学习最新的Go技能树
  • ?阅读更多 Go 教程
  • ?加入我们的 Discord 或发推文@WeAreLabEx

以上是出发时间和持续时间|编程教程的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板