網站首頁 編程語言 正文
golang中并沒有像java一樣提供類似yyyy-MM-dd HH:mm:ss
格式的操作,而是將其定義為golang的誕生時間:
2006-01-02 15:04:05 -0700 MST
注意這在golang的日期格式化里不是一個具體日期,而是格式,這樣如果我們需要格式化日期,可以如下操作
timeNow := time.Now() fmt.Println("yyyy-MM-dd HH:mm:ss" ,timeNow.Format("2006-01-02 15:04:05")) // 打印: yyyy-MM-dd HH:mm:ss: 2022-05-11 14:24:19
接下來說下Time
中的幾個方法:
Time.Unix() 獲取時間秒數,返回的是unix時間秒
fmt.Println("from 1970-01-01 to now seconds: ",int32(time.Now().Unix()))
Time.Date() 返回年月日:
year,month,day := timeNow.Date() fmt.Println(year,month,day) // 注意打印的是: 2022 May 11
Time.AddDate 時間增減:
timeLast := timeNow.AddDate(0,0,-1) fmt.Println(timeLast.Format("2006-01-02 15:04:05"))
Time.Add 增加指定的時間,可以精確到納秒
time2 := timeNow.Add(time.Duration(2000*time.Millisecond)) fmt.Println(time2.Format("2006-01-02 15:04:05"))
Time.After 是否在指定時間之后,如果是返回true Time.Before 是否在指定時間之前,如果是返回true time.Parse 按照指定格式將字符串轉換為日期:
time2,err := time.Parse("2006-01-02 15:04:05","2022-05-11 15:04:05") if err != nil { fmt.Println(err) } fmt.Println(time2.Format("2006-01-02 15:04:05"))
補充:go語言時間和日期的轉化
go 語言中使用time.Time表示時間。我們可以通過time.Now函數獲取當前的時間對象,然后從時間對象中可以獲取到年、月、日、時、分、秒等信息。
package main import ( ?? ?"fmt" ?? ?"time" ) func main() { ?? ?t := time.Now() // 獲取當前時間 ?? ?fmt.Printf("當前時間:%v\n", t) ?? ?fmt.Println("年", t.Year()) ?? ?fmt.Println("月", t.Month()) ?? ?fmt.Println("日", t.Day()) ?? ?fmt.Println("時", t.Hour()) ?? ?fmt.Println("分", t.Minute()) ?? ?fmt.Println("秒", t.Second()) }
輸出
當前時間:2022-05-19 21:38:39.7367663 +0800 CST m=+0.001805001
年 2022
月 May?
日 19 ?
時 21 ?
分 38 ?
time 包中定義的時間間隔類型的常量如下:
const ( ? ? Nanosecond ?Duration = 1 ? ? Microsecond ? ? ? ? ?= 1000 * Nanosecond ? ? Millisecond ? ? ? ? ?= 1000 * Microsecond ? ? Second ? ? ? ? ? ? ? = 1000 * Millisecond ? ? Minute ? ? ? ? ? ? ? = 60 * Second ? ? Hour ? ? ? ? ? ? ? ? = 60 * Minute )
例如:time.Hour表示1小時,time.Second表示1秒。
總結
原文鏈接:https://blog.csdn.net/LeoHan163/article/details/124710250
相關推薦
- 2023-03-20 Redis使用Bitmap的方法實現_Redis
- 2022-03-20 基于ABP框架實現RBAC(角色訪問控制)_實用技巧
- 2022-06-11 Python?tkinter庫圖形繪制例子分享_python
- 2022-09-06 C語言超詳細講解猜數字游戲的實現_C 語言
- 2021-12-11 C語言中數據在內存如何存儲_C 語言
- 2022-05-21 ASP.NET?MVC中兩個配置文件的作用詳解_基礎應用
- 2022-08-15 Python自制隨機數生成算法
- 2023-02-10 C/C++?extern關鍵字用法示例全面解析_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支