Skip to content

Instantly share code, notes, and snippets.

@myphpmaster
Forked from kmaida/convert-UNIX-timestamp.js
Last active August 29, 2015 14:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myphpmaster/d0fa59d3780cd32bff8d to your computer and use it in GitHub Desktop.
Save myphpmaster/d0fa59d3780cd32bff8d to your computer and use it in GitHub Desktop.
Convert UNIX timestamp to local time with timezone UTC+/- code
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;
}
// Added timezone
tz = d.getTimezoneOffset();
if(tz==0)
tzs = ' UTC';
else if(tz>0)
tzs = ' UTC-';
else
tzs = ' UTC+';
// get absolute value
tz = Math.abs(tz);
tzhh = Math.floor(tz/60);
tzmm = tz - tzhh*60;
if(tzmm==0)
tzmm = '00';
// ie: 2013-02-18, 8:35 AM (Added UTC+8:00)
time = yyyy + '-' + mm + '-' + dd + ', ' + h + ':' + min + ' ' + ampm + ' ' + tzs + tzhh + ':' + tzmm;
return time;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment