Last active
March 16, 2023 09:31
-
-
Save kmaida/6045266 to your computer and use it in GitHub Desktop.
Convert a UNIX timestamp to user's local time via JavaScript
This file contains 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
function convertTimestamp(timestamp) { | |
var d = new Date(timestamp * 1000), // Convert the passed timestamp to milliseconds | |
yyyy = d.getFullYear(), | |
mm = ('0' + (d.getMonth() + 1)).slice(-2), // Months are zero based. Add leading 0. | |
dd = ('0' + d.getDate()).slice(-2), // Add leading 0. | |
hh = d.getHours(), | |
h = hh, | |
min = ('0' + d.getMinutes()).slice(-2), // Add leading 0. | |
ampm = 'AM', | |
time; | |
if (hh > 12) { | |
h = hh - 12; | |
ampm = 'PM'; | |
} else if (hh === 12) { | |
h = 12; | |
ampm = 'PM'; | |
} else if (hh == 0) { | |
h = 12; | |
} | |
// ie: 2013-02-18, 8:35 AM | |
time = yyyy + '-' + mm + '-' + dd + ', ' + h + ':' + min + ' ' + ampm; | |
return time; | |
} |
@vortex14
hiii,
the guys who got weird return values, please consider remove the multiplication by 1000 and set it as below
var d = new Date(timestamp)
new Date(timestamp * 1000), new Date(timestamp )
...that's what I was looking for! Thanks @AryanSafi
(If converting from milliseconds, just drop the * 1000
.)
thanks mann,
btw i have a suggestion on this line,
mm = ('0' + (d.getMonth() + 1)).slice(-2),
why not try using .padStart(2, "0")
instead to pad the "0"s
mm = `${d.getMonth() + 1}`.padStart(2, "0"),
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks mate