获取当前时间

func Now

func Now() Time
  • 1

Now returns the current local time.

func (Time) UTC

func (t Time) UTC() Time
  • 1

UTC returns t with the location set to UTC.

func (Time) Unix

func (t Time) Unix() int64
  • 1

Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC.

func (Time) UnixNano

func (t Time) UnixNano() int64
  • 1

UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC.

看到Unix和UnixNano的区别了吧,就是精度不同而已:

package main

import (
"fmt"
"strconv"
"time"
) func main() {
t := time.Now()
fmt.Println(t) fmt.Println(t.UTC().Format(time.UnixDate)) fmt.Println(t.Unix()) timestamp := strconv.FormatInt(t.UTC().UnixNano(), 10)
fmt.Println(timestamp)
timestamp = timestamp[:10]
fmt.Println(timestamp)
}

输出: 
2017-06-21 11:52:29.0826692 +0800 CST 
Wed Jun 21 03:52:29 UTC 2017 
1498017149 
1498017149082669200 
1498017149

时间格式化字符串转换

func Parse

package main

import (
"fmt"
"strconv"
"time"
) func main() {
const longForm = "Jan 2, 2006 at 3:04pm (MST)"
t, _ := time.Parse(longForm, "Jun 21, 2017 at 0:00am (PST)")
fmt.Println(t) const shortForm = "2006-Jan-02"
t, _ = time.Parse(shortForm, "2017-Jun-21")
fmt.Println(t) t, _ = time.Parse("01/02/2006", "06/21/2017")
fmt.Println(t)
fmt.Println(t.Unix()) i, err := strconv.ParseInt("1498003200", 10, 64)
if err != nil {
panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm) var timestamp int64 = 1498003200
tm2 := time.Unix(timestamp, 0)
fmt.Println(tm2.Format("2006-01-02 03:04:05 PM"))
fmt.Println(tm2.Format("02/01/2006 15:04:05 PM"))
}

输出: 
2017-06-21 00:00:00 +0000 PST 
2017-06-21 00:00:00 +0000 UTC 
2017-06-21 00:00:00 +0000 UTC 
1498003200 
2017-06-21 08:00:00 +0800 CST 
2017-06-21 08:00:00 AM 
21/06/2017 08:00:00 AM

再看一个例子:

package main

import (
"fmt"
"strings"
"time"
) func main() { var dates [4]time.Time dates[0], _ = time.Parse("2006-01-02 15:04:05.000000000 MST -07:00", "1609-09-12 19:02:35.123456789 PDT +03:00")
dates[1], _ = time.Parse("2006-01-02 03:04:05 PM -0700", "1995-11-07 04:29:43 AM -0209")
dates[2], _ = time.Parse("PM -0700 01/02/2006 03:04:05", "AM -0209 11/07/1995 04:29:43")
dates[3], _ = time.Parse("Time:Z07:00T15:04:05 Date:2006-01-02 ", "Time:-03:30T19:18:35 Date:2119-10-29") defaultFormat := "2006-01-02 15:04:05 PM -07:00 Jan Mon MST" formats := []map[string]string{
{"format": "2006", "description": "Year"},
{"format": "06", "description": "Year"}, {"format": "01", "description": "Month"},
{"format": "1", "description": "Month"},
{"format": "Jan", "description": "Month"},
{"format": "January", "description": "Month"}, {"format": "02", "description": "Day"},
{"format": "2", "description": "Day"}, {"format": "Mon", "description": "Week day"},
{"format": "Monday", "description": "Week day"}, {"format": "03", "description": "Hours"},
{"format": "3", "description": "Hours"},
{"format": "15", "description": "Hours"}, {"format": "04", "description": "Minutes"},
{"format": "4", "description": "Minutes"}, {"format": "05", "description": "Seconds"},
{"format": "5", "description": "Seconds"}, {"format": "PM", "description": "AM or PM"}, {"format": ".000", "description": "Miliseconds"},
{"format": ".000000", "description": "Microseconds"},
{"format": ".000000000", "description": "Nanoseconds"}, {"format": "-0700", "description": "Timezone offset"},
{"format": "-07:00", "description": "Timezone offset"},
{"format": "Z0700", "description": "Timezone offset"},
{"format": "Z07:00", "description": "Timezone offset"}, {"format": "MST", "description": "Timezone"}} for _, date := range dates {
fmt.Printf("\n\n %s \n", date.Format(defaultFormat))
fmt.Printf("%-15s + %-12s + %12s \n", strings.Repeat("-", 15), strings.Repeat("-", 12), strings.Repeat("-", 12))
fmt.Printf("%-15s | %-12s | %12s \n", "Type", "Placeholder", "Value")
fmt.Printf("%-15s + %-12s + %12s \n", strings.Repeat("-", 15), strings.Repeat("-", 12), strings.Repeat("-", 12)) for _, f := range formats {
fmt.Printf("%-15s | %-12s | %-12s \n", f["description"], f["format"], date.Format(f["format"]))
}
fmt.Printf("%-15s + %-12s + %12s \n", strings.Repeat("-", 15), strings.Repeat("-", 12), strings.Repeat("-", 12))
}
}

time包的一些其他用法

time包很强大,这里不能整个篇幅的进行介绍,可以自己去看官方的文档。

func Date

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
  • 1

time常用方法

After(u Time) bool 
时间类型比较,是否在Time之后

Before(u Time) bool 
时间类型比较,是否在Time之前

Equal(u Time) bool 
比较两个时间是否相等

IsZero() bool 
判断时间是否为零值,如果sec和nsec两个属性都是0的话,则该时间类型为0

Date() (year int, month Month, day int) 
返回年月日,三个参数

Year() int 
返回年份

Month() Month 
返回月份.是Month类型

Day() int 
返回多少号

Weekday() Weekday 
返回星期几,是Weekday类型

ISOWeek() (year, week int) 
返回年份,和该填是在这年的第几周.

Clock() (hour, min, sec int) 
返回小时,分钟,秒

Hour() int 
返回小时

Minute() int 
返回分钟

Second() int 
返回秒数

Nanosecond() int 
返回纳秒

应用:

package main

import "fmt"
import "time" func main() {
p := fmt.Println now := time.Now()
p(now) then := time.Date(
2017, 06, 21, 20, 34, 58, 0, time.UTC)
p(then) p(then.Year())
p(then.Month())
p(then.Day())
p(then.Hour())
p(then.Minute())
p(then.Second())
p(then.Nanosecond())
p(then.Location()) p(then.Weekday()) p(then.Before(now))
p(then.After(now))
p(then.Equal(now)) diff := now.Sub(then)
p(diff) p(diff.Hours())
p(diff.Minutes())
p(diff.Seconds())
p(diff.Nanoseconds()) p(then.Add(diff))
p(then.Add(-diff))
}

输出: 
2017-06-21 13:22:36.5138633 +0800 CST 
2017-06-21 20:34:58 +0000 UTC 
2017 
June 
21 
20 
34 
58 

UTC 
Wednesday 
false 
true 
false 
-15h12m21.4861367s 
-15.205968371305556 
-912.3581022783334 
-54741.4861367 
-54741486136700 
2017-06-21 05:22:36.5138633 +0000 UTC 
2017-06-22 11:47:19.4861367 +0000 UTC

////////////////////////////////////////////  计算时间差  / ////////////////////////////////////////////////////////

package main

import (
"fmt"
"strings"
"time"
) func main() {
// Add 时间相加
now := time.Now()
// ParseDuration parses a duration string.
// A duration string is a possibly signed sequence of decimal numbers,
// each with optional fraction and a unit suffix,
// such as "300ms", "-1.5h" or "2h45m".
// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
// 10分钟前
m, _ := time.ParseDuration("-1m")
m1 := now.Add(m)
fmt.Println(m1) // 8个小时前
h, _ := time.ParseDuration("-1h")
h1 := now.Add(8 * h)
fmt.Println(h1) // 一天前
d, _ := time.ParseDuration("-24h")
d1 := now.Add(d)
fmt.Println(d1) printSplit(50) // 10分钟后
mm, _ := time.ParseDuration("1m")
mm1 := now.Add(mm)
fmt.Println(mm1) // 8小时后
hh, _ := time.ParseDuration("1h")
hh1 := now.Add(hh)
fmt.Println(hh1) // 一天后
dd, _ := time.ParseDuration("24h")
dd1 := now.Add(dd)
fmt.Println(dd1) printSplit(50) // Sub 计算两个时间差
subM := now.Sub(m1)
fmt.Println(subM.Minutes(), "分钟") sumH := now.Sub(h1)
fmt.Println(sumH.Hours(), "小时") sumD := now.Sub(d1)
fmt.Printf("%v 天\n", sumD.Hours()/24) } func printSplit(count int) {
fmt.Println(strings.Repeat("#", count))
}

golang 时间戳 时间格式化 获取当前时间 timestamp 计算时间差的更多相关文章

  1. time模块:时间戳和格式化好的时间表示方法及互相转换方法

    1.导入time模块   import time 2.获取当前时间的时间戳   time.time() 3.获取当前格式化好的时间   time.strftime(想要获取的格式) 4.时间戳和格式化 ...

  2. 【转】python 输入一个时间,获取这个时间的下一秒

    原文:https://blog.csdn.net/l_d_56/article/details/84832198 输入一个时间,获取这个时间的下一秒 PS:下面代码使用于 python 2.7 tim ...

  3. 特殊字符转义&时间格式化&获取URL参数

    /*特殊字符转义*/ function htmlspecialchars (str) { var str = str.toString().replace(/&/g, "&& ...

  4. Java 获取各时区时间,获取当前时间到格林威治时间1970年01月01日00时00分00秒的秒数

    格林威治时间即UTC/GMT时间,1970年01月01日00时00分00秒(即UTC+8的北京时间1970年01月01日08时00分00秒)计算代码如下: /** * 获取指定时间到格林威治时间的秒数 ...

  5. js 的date的format时间,获取当前时间,前一天的日期

    Date.prototype.Format = function (fmt) { //author: meizz var o = { "M+": this.getMonth() + ...

  6. C# 获取两个时间段之间的所有时间与获取当前时间所在的季度开始和结束时间

    一:C# 获取两个时间段之间的所有时间 public List<string> GetTimeList(string rq1, string rq2) { List<string&g ...

  7. MySQL时间函数-获取当前时间-时间差

    MySQL中获取当前时间为now(),不同于sqlserver getdate(). SQLServer转MySQL除变化top 1 -> limit 1之后报错: limit [Err] 15 ...

  8. redis基本操作,基于StringRedisTemplate,存储,取值,设置超时时间,获取超时时间,插入list操作

    @Autowired private StringRedisTemplate stringRedisTemplate; @GetMapping("/test") void test ...

  9. nodejs 模块moment格式化时间,获取当前时间的前一天时间

    var moment = require('moment'); moment.locale('zh-cn'); var today = {}; var _today = moment(); today ...

随机推荐

  1. 聊一聊Iterable与Iterator的那些事!

    前言 欢迎关注公众号:Coder编程 获取最新原创技术文章和相关免费学习资料,随时随地学习技术知识! 在上一篇文章通过面试题,让我们来了解Collection,我们会发现Collection接口之上还 ...

  2. 解决SSH连接linux时长时间不操作自动断开

    最近重装Linux系统,但是这次ssh连接云服务区Linux系统时,经常出现一段时间不操作,连接自动中断,表现为光标还在闪动,但是却无法操作.只好关闭终端,重新连接,很是麻烦. 为此,通过网络查找,找 ...

  3. Ruby(1):入门

    安装: 一般来说linux会自动装ruby,可以通过: ruby -v 来查看ruby版本 直接使用ruby命令的话,是用来执行ruby文件的.如果要打开交互式ruby解释器.只需要在控制台输入:ir ...

  4. [转]Upgrading to Async with Entity Framework, MVC, OData AsyncEntitySetController, Kendo UI, Glimpse & Generic Unit of Work Repository Framework v2.0

    本文转自:http://www.tuicool.com/articles/BBVr6z Thanks to everyone for allowing us to give back to the . ...

  5. [学习线路] 零基础学习hadoop到上手工作线路指导(初级篇)

    about云课程最新课程Cloudera课程   零基础学习hadoop,没有想象的那么困难,也没有想象的那么容易.在刚接触云计算,曾经想过培训,但是培训机构的选择就让我很纠结.所以索性就自己学习了. ...

  6. SQL Serever学习14——存储过程和触发器

    存储过程 在数据库中很多查询都是大同小异,编写他们费时费力,将他们保存起来,以后执行就很方便了,把SQL语句“封装”起来. 存储过程的概念 存储过程是一组SQL语句集,经过编译存储,可以”一次编译,多 ...

  7. Python——基本的方法

    格式化 我们经常会输出类似'亲爱的xxx你好!你xx月的话费是xx,余额是xx'之类的字符串,而xxx的内容都是根据变量变化的,所以,需要一种简便的格式化字符串的方式 >>> 'He ...

  8. MVC中学到的小知识(MVC中的跳转,传参)

    1.mvc中视图中的href="XXX",这个XXX是控制器地址,不是另一个视图.(这里的href语句只能转向控制器,不能直接转向视图),如果要实现转向视图,可以先转到控制器,然后 ...

  9. Java基础——封装类

    封装类的由来: 为了将基本类型以对象行使存在,java对八个基本类型提供了引用类型,这八个引用类型称为基本类型的“包装类”. 八个基本类型对应的封装类: int           --->   ...

  10. CODEFORCES 429B 动态规划

    http://codeforces.com/problemset/problem/429/B 可以参考这篇文章: http://blog.csdn.net/pure_lady/article/deta ...