分享
  1. 首页
  2. 文章

golang编程之时间编程

yavobo · · 3908 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

本文转载于:http://blog.chinaunix.net/uid-24774106-id-4006530.html

编程离不开时间,时间管理,严格的说分成两块,一个是当前的时刻,对应的是一个点,还有是一段时间间隔。本文简单的讲讲go的时间相关的编程,比较简单,高手可以一笑而过。

golang对时间的支持,是package time做的事儿,里面有好多的函数,我就不一一举例学习,毕竟这是官方文档干的事情。我们初步的学习下常用的函数。
第一个是UNIX epoch time,确切的说就是自1970年01月01日 00:00:00 GMT以来的秒数,不知道如何获取的,可以在shell下执行 date +%s
  1. manu@manu-hacks:~/code/go/self$ date +%s
  2. 1385131172
熟悉Linux下C编程的就是time函数的返回值:
  1. #include <time.h>

  2. time_t now = time(NULL);
golang中一个很重要的表征时间的数据类型是Time,基本就是三个成员变量 sec ,nsec,Location,详细意思可以参看注释。
  1. type Time struct {
  2. // sec gives the number of seconds elapsed since
  3. // January 1, year 1 00:00:00 UTC.
  4. sec int64

  5. // nsec specifies a non-negative nanosecond
  6. // offset within the second named by Seconds.
  7. // It must be in the range [0, 999999999].
  8. nsec int32

  9. // loc specifies the Location that should be used to
  10. // determine the minute, hour, month, day, and year
  11. // that correspond to this Time.
  12. // Only the zero Time has a nil Location.
  13. // In that case it is interpreted to mean UTC.
  14. loc *Location
  15. }
OK,如何取到UNIX epoch time.
  1. now := time.Now()

用time package中Now()函数获取到当前的时间信息,Now()函数非常的重要,他是后面一切转换的起始点。从Now()我们获取到了Time,从Time类型我们从容的获取到UNIX epoch time ,自然获取到year ,month ,day,weekday, hour,minute,second,nanosecond.
获取UNIX epoch time:
  1. var epoch_seconds int64 = now.Unix()
获取Year
  1. func (t Time) Year() int

  2. cur_year := now.Year()
获取Month
  1. func (t Time) Month() Month

  2. cur_month := now.Month()

  3. if cur_month == time.November {
  4. ...
  5. }
Month是int类型,fmt.Printf("%v") 或者fmt.Println可以打印出November来,同时Month type有String()函数,输出"November"这样的字符串
  1. const (
  2. January Month = 1 + iota
  3. February
  4. March
  5. April
  6. May
  7. June
  8. July
  9. August
  10. September
  11. October
  12. November
  13. December
  14. )
year mon day,这些都可以在Date函数中一并返回:
  1. func (t Time) Date() (year int, month Month, day int)

  2. year,mon,day = now.Date()
获取Hour
    1. func (t Time) Hour() int
  1. cur_hour := now.Hour()

Minute可以通过Minute()返回,second可以通过Second()返回。
time还提供了Clock()的同时返回 hour,minute,second = now.Clock().
在C语言中,我们用gmtime_r获取UTC时间,localtime_r获取本地时间,Golang我们也可以做到
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>


  4. int main()
  5. {
  6. time_t now = time(NULL);
  7. printf("elapsed %d second since 1970年01月01日 00:00:00\n",now);

  8. struct tm now_utc_tm ={0};
  9. if (gmtime_r(&now,&now_utc_tm) != NULL)
  10. {
  11. printf("UTC time is %d-%02d-%02d %02d:%02d:%02d %s\n",
  12. now_utc_tm.tm_year+1900,now_utc_tm.tm_mon,
  13. now_utc_tm.tm_mday,now_utc_tm.tm_hour,
  14. now_utc_tm.tm_min,now_utc_tm.tm_sec,now_utc_tm.tm_zone);
  15. }

  16. struct tm now_local_tm = {0} ;
  17. if(localtime_r(&now,&now_local_tm) != NULL)
  18. {
  19. printf("local time is %d-%02d-%02d %02d:%02d:%02d %s\n",
  20. now_local_tm.tm_year+1900,now_local_tm.tm_mon,
  21. now_local_tm.tm_mday,now_local_tm.tm_hour,
  22. now_local_tm.tm_min, now_local_tm.tm_sec,now_local_tm.tm_zone);
  23. }

  24. return 0;

  25. }
golang的版本是:
  1. package main

  2. import "fmt"
  3. import "time"



  4. func main(){

  5. now := time.Now()
  6. year,mon,day := now.UTC().Date()
  7. hour,min,sec := now.UTC().Clock()
  8. zone,_ := now.UTC().Zone()
  9. fmt.Printf("UTC time is %d-%d-%d %02d:%02d:%02d %s\n",
  10. year,mon,day,hour,min,sec,zone)

  11. year,mon,day = now.Date()
  12. hour,min,sec = now.Clock()
  13. zone,_ = now.Zone()
  14. fmt.Printf("local time is %d-%d-%d %02d:%02d:%02d %s\n",
  15. year,mon,day,hour,min,sec,zone)
  16. }
输出分别是:

  1. C版本的输出
  2. ------------------
  3. UTC time is 2013-10-22 15:49:18 GMT
  4. local time is 2013-10-22 23:49:18 CST

  5. go版本的输出
  6. ---------------------
  7. UTC time is 2013-11-22 15:51:22 UTC
  8. local time is 2013-11-22 23:51:22 CST
-------------------------------------------------------------------------------------------------------------------------------------------------------------
我们另一个关心的话题,是时间间隔,比如我们profile一个以非常耗时的function,我们会在函数开始前记下时刻值,函数结束后,再次记录下时刻值,然后两者的差值,就是函数运行时间。
这表明Time是可以相减的,
  1. start_time := time.Now()
  2. expensive_function
  3. end_time :=time.Now()

  4. var duration Duration = end_time.Sub(start_time)
Duration是一种数据类型,其实是个int64类型,表征的是两个时刻之间的纳秒数。
  1. type Duration int64

  2. const (
  3. Nanosecond Duration = 1
  4. Microsecond = 1000 * Nanosecond
  5. Millisecond = 1000 * Microsecond
  6. Second = 1000 * Millisecond
  7. Minute = 60 * Second
  8. Hour = 60 * Minute
  9. )
Duration类型有Minutes()/Second()/Nanoseconds(), 将duration折算成分钟/秒/纳秒。
  1. now := time.Now()
  2. time.Sleep(3*time.Second);
  3. end_time := time.Now()

  4. var dur_time time.Duration = end_time.Sub(now)
  5. var elapsed_min float64 = dur_time.Minutes()
  6. var elapsed_sec float64 = dur_time.Seconds()
  7. var elapsed_nano int64 = dur_time.Nanoseconds()
  8. fmt.Printf("elasped %f minutes or \nelapsed %f seconds or \nelapsed %d nanoseconds\n",
  9. elapsed_min,elapsed_sec,elapsed_nano)
输出如下:
  1. elasped 0.050005 minutes or
  2. elapsed 3.000292 seconds or
  3. elapsed 3000292435 nanoseconds
------------------------------------------------------------------------------------------------------------------------------------------------
第二部分描述Duration明显用到了Sleep()函数,这个函数是以纳秒为单位的,相当于C语言中的nanosleep()
  1. #include <time.h>
  2. nanosleep(): _POSIX_C_SOURCE >= 199309L

  3. int nanosleep(const struct timespec *req, struct timespec *rem);

#include <unistd.h>


unsigned int sleep(unsigned int seconds);


Go中的time.Sleep一律是以纳秒为单位的,当然本质是Duration类型:
如果sleep 3秒中需要写成:
  1. time.Sleep(3000000000)
这太不方便了,所以,Golang可以写成
  1. time.Sleep(3*time.Second);
这样可读性就好多了,当然还有time.Minute,time.Hour

这个time package还有很多其他的内容,我就不一一赘述了。

参考文献:
1 golang package time

有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:yavobo

查看原文:golang编程之时间编程

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
3908 次点击
上一篇:golang发邮件
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏