Golang time conversion

timeLayout := "The 2006-01-02 15:04:05"
Copy the code

1. Obtain the server time

fmt.Println(time.Now().Format(timeLayout))
Copy the code

2. Obtain UTC time

fmt.Println(time.Now().UTC().Format(timeLayout))
Copy the code

3. Change the server time to UTC time

timeStr := "The 2021-05-18 12:00:00"          // Consider the server time
location, _ := time.LoadLocation("Local") // timeStr is Beijing time
localTime, _ := time.ParseInLocation(timeLayout, timeStr, location)
fmt.Println(localTime.UTC().Format(timeLayout)) // Convert to UTC time
Copy the code

Note: Notice the value of timeStr, at this point we treat it as the server time, so time.loadLocation (“Local”) uses Local

4. Convert UTC time to server time

timeStr := "The 2021-05-18 12:00:00"        // Consider the UTC time
location, _ := time.LoadLocation("UTC") // timeStr is Beijing time, note UTC
localTime, _ := time.ParseInLocation(timeLayout, timeStr, location)
fmt.Println(localTime.Local().Format(timeLayout)) // Change the time to Local server
Copy the code

Note: Notice the value of timeStr, at this time we treat it as UTC time, so time.loadLocation (“UTC”) uses Local

Golang time comparison

timeLayout := "The 2006-01-02 15:04:05"
Copy the code
timeStr := "The 2021-05-17 11:00:00"          // Consider the server time
location, _ := time.LoadLocation("Local") // timeStr is Beijing time
localTime, _ := time.ParseInLocation(timeLayout, timeStr, location)
fmt.Println(localTime.UTC().Format(timeLayout)) // Convert to UTC time

compareTimeStr := "The 2021-05-17 02:00:00" // Consider the UTC time
location, _ = time.LoadLocation("UTC")  // timeStr is Beijing time, note UTC
compareTime, _ := time.ParseInLocation(timeLayout, compareTimeStr, location)
fmt.Println(compareTime.Local().Format(timeLayout)) // Convert to server time
fmt.Println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -")

fmt.Println(compareTime.Before(localTime)) // Before will be consistent with the time baseline
fmt.Println(compareTime.After(localTime))  // After will unify the time reference point
Copy the code

Note: Before After will unify the time reference point, so you don’t need to worry about the time comparison error caused by the time zone problem, but pay attention to the time zone problem when converting to golang time. time.