Skip to content

Instantly share code, notes, and snippets.

@kmaida
Last active March 16, 2023 09:31
Show Gist options
  • Save kmaida/6045266 to your computer and use it in GitHub Desktop.
Save kmaida/6045266 to your computer and use it in GitHub Desktop.
Convert a UNIX timestamp to user's local time via JavaScript
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;
}
@dylanvalade
Copy link

This is simple, clear and commented. Thank you!

@vortex14
Copy link

convertTimestamp(new Date())
Bad result: "47830-08-05, 5:27 PM"

@rustanacexd
Copy link

@vortex14 you not should be entering new date as a parameter, it should be a valid unix timestamp

@AryanSafi
Copy link

var d = new Date(timestamp * 1000) just remove 1000 from new Date(timestamp * 1000), new Date(timestamp )

@druby-luke
Copy link

Thanks :D helped me out allot

Copy link

ghost commented Jan 31, 2017

Thanks ;-)

@advancedsoftwarecanada
Copy link

Great function! Would be nice to see days.

@advancedsoftwarecanada
Copy link

Customized the function with normal date options, http://www.w3schools.com/jsref/jsref_obj_date.asp

This my help some one in the future :)

if(day==0){ day="Sunday"; }
if(day==1){ day="Monday"; }
if(day==2){ day="Tuesday"; }
if(day==3){ day="Wednesday"; }
if(day==4){ day="Thursday"; }
if(day==5){ day="Friday"; }
if(day==6){ day="Saturday"; }

				return time = day+" at "+ h + ':' + min + ' ' + ampm;

@custer-stuff
Copy link

thanks!

@amyeckert
Copy link

This is great, thanks for sharing !

@amackintosh
Copy link

amackintosh commented Nov 6, 2017

Without testing, you should be able to fix that with:

convertTimestamp(new Date().valueOf()) //converts to unix time in ms

instead of:

convertTimestamp(new Date())
Bad result: "47830-08-05, 5:27 PM"

Here is another version that you could make prettier by using some of the logic above:

export default (ts) => {
  const rawDate = new Date(ts).toISOString().split('T')
  const date = `${rawDate[0]}`
  const rawTime = rawDate[1].split(':')
  const time = `${(rawTime[0])}:${rawTime[1]}`
  return `${date} at ${time}`
}

@Housecaz
Copy link

Hi,

How can I call this function multiple times? For example, if I call this function in a Flask Template via:

<div id="datetime" class="col-md-4"><script>document.getElementById("datetime").innerHTML = convertTimestamp({{ i['TrialExpirationTime'] }});</script></div>

I only get the first result converted. The rest of the templates are empty.

EG, I have:
<div id="datetime" class="col-md-4"><script>document.getElementById("datetime").innerHTML = convertTimestamp({{ i['TrialExpirationTime'] }});</script></div>

<div id="datetime" class="col-md-4"><script>document.getElementById("datetime").innerHTML = convertTimestamp({{ i['TrialExpirationTime'] }});</script></div>

<div id="datetime" class="col-md-4"><script>document.getElementById("datetime").innerHTML = convertTimestamp({{ i['TrialExpirationTime'] }});</script></div>

only the first one converts to "2020-02-02, 12:00 AM"

@grantnoe
Copy link

grantnoe commented May 24, 2018

@Housecaz

By the HTML standard you're only supposed to have one tag of a particular ID. You have three div tags all with an ID of "datetime". My guess would be that your JS is running the same function each time, but always on the first ID that it sees in the DOM. My recommendation: just have one <script> element at the bottom of your HTML body. Convert all the datetime IDs to classes instead, and run something like this:
var converted = convertTimestamp({{ i['TrialExpirationTime'] }}), objects = document.getElementsByClassName("datetime"); for (var i = 0; i < objects.length; i++) { objects[i].innerHTML = converted; }

@lConstantine
Copy link

thanks mate

@95Rajitha
Copy link

@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)

@ashleedawg
Copy link

ashleedawg commented Sep 21, 2021

new Date(timestamp * 1000), new Date(timestamp )

...that's what I was looking for! Thanks @AryanSafi

(If converting from milliseconds, just drop the * 1000.)

@andrehadianto
Copy link

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