Created
July 1, 2022 07:36
-
-
Save knadh/544cb60cc426cf62b4dcfda00bc254b5 to your computer and use it in GitHub Desktop.
Convert a unix (milli) timestamp to year, month, day ... without using the standard library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
fmt.Println(unixToTime(time.Now().UnixMilli())) | |
} | |
// unixToTime takes a unix millisecond timestamp (time.UnixMilli()) | |
// parses it and returns year, month, day, hour, minute, second (UTC). | |
// | |
// WARNING: ONLY USE something dodgy like this if there's an extremely | |
// specific reason not to use the standard library. | |
func unixToTime(timestamp int64) (int, int, int, int, int, int) { | |
var ( | |
daysPerMonth = []int{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} | |
days = int(timestamp / 86400000) | |
year = 1970 | |
) | |
daysPerYear := 365 | |
for { | |
dy := getDaysPerYear(year) | |
if days < dy { | |
break | |
} | |
days -= dy | |
year++ | |
daysPerYear = dy | |
} | |
month := 1 | |
for { | |
dm := daysPerMonth[month] | |
// Adjust Feb day count for leapyear. | |
if month == 2 && daysPerYear == 366 { | |
dm = 29 | |
} | |
if days < dm { | |
break | |
} | |
days -= dm | |
month++ | |
} | |
var ( | |
day = int(days) + 1 | |
secondsRemaining = int(timestamp / 1000 % 86400) | |
hour = secondsRemaining / 3600 | |
minute = (secondsRemaining / 60) % 60 | |
second = secondsRemaining % 60 | |
) | |
return year, month, day, hour, minute, second | |
} | |
func getDaysPerYear(year int) int { | |
if year%400 == 0 || (year%4 == 0 && year%100 != 0) { | |
return 366 | |
} | |
return 365 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment