Golang – Get the converted second, millisecond, nanosecond timestamp output of the current time format
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now() //2019-07-31 13:55:21.3410012 +0800 CST m=+0.006015601
fmt.Println(t.Format("20060102150405"))
//current timestamp
t1 := time.Now().Unix() //1564552562
fmt.Println(t1)
// Convert timestamp to specific time
fmt.Println(time.Unix(t1, 0).String())
//Basically formatted time representation
fmt.Println(time.Now().String()) //2019-07-31 13:56:35.7766729 +0800 CST m=+0.005042501
fmt.Println(time.Now().Format("2006-01-02")) //2019-07-31
fmt.Println(time.Now().Format("2006-01-02 15:04:05")) //2019-07-31 13:57:52
//get week number
_, week := time.Now().ISOWeek()
//get year, month, day
year, month, day := rwTools.DateYmdInts()
}
// Timestamp to year, month, day, hour, minute, second
func DateFormat(timestamp int) string {
tm := time.Unix(int64(timestamp), 0)
return tm.Format("2006-01-02 15:04")
}
//timestamp to year month day
func DateFormatYmd(timestamp int) string {
tm := time.Unix(int64(timestamp), 0)
return tm.Format("2006-01-02")
}
//Get the current year and month
func DateYmFormat() string {
tm := time.Now()
return tm.Format("2006-01")
}
//Get the year, month, day, hour, minute and second (string type)
func DateNowFormatStr() string {
tm := time.Now()
return tm.Format("2006-01-02 15:04:05")
}
//timestamp
func DateUnix() int {
t := time.Now().Local().Unix()
return int(t)
}
//Get the year, month, day, hour, minute and second (time type)
func DateNowFormat() time.Time {
tm := time.Now()
return tm
}
//get week number
func DateWeek() int {
_, week := time.Now().ISOWeek()
return week
}
//get year, month, day
func DateYMD() (int,int, int) {
year, month, day := DateYmdInts()
return year,month,day
}
// get year month day
func DateYmdFormat() string {
tm := time.Now()
return tm.Format("2006-01-02")
}
// Get the year month day of the date
func DateYmdInts() (int, int, int) {
timeNow := time.Now()
year, month, day := timeNow.Date()
return year, int(month), day
}
2.Golang’s time package: second, millisecond, nanosecond timestamp output
time stamp
10 digit is in seconds;
13 digit is in milliseconds;
The 19 digit number is in nanoseconds;
package main
import (
"time"
"fmt"
)
func main() {
fmt.Printf("Timestamp (seconds): %v;\n", time.Now().Unix())
fmt.Printf("Timestamp (nanoseconds): %v;\n",time.Now().UnixNano())
fmt.Printf("Timestamp (milliseconds): %v;\n",time.Now().UnixNano() / 1e6)
fmt.Printf("Timestamp (nanoseconds to seconds): %v;\n",time.Now().UnixNano() / 1e9)
}
"""
output result
timestamp (seconds): 1530027865;
Timestamp (nanoseconds): 1530027865231834600;
timestamp (milliseconds): 1530027865231;
timestamp (nanoseconds to seconds): 1530027865;
"""