Skip to content

Instantly share code, notes, and snippets.

@MurhafSousli
Created October 12, 2017 03:59
Show Gist options
  • Save MurhafSousli/dd45da2d82a856c6c65e17335b9e65ba to your computer and use it in GitHub Desktop.
Save MurhafSousli/dd45da2d82a856c6c65e17335b9e65ba to your computer and use it in GitHub Desktop.
Date and time js function
//using your function (passing in date)
function formatAMPM(date) {
let days = date.getUTCDate();
let month = date.getUTCMonth() + 1;
const year = date.getUTCFullYear();
let hours = date.getHours();
let minutes = date.getMinutes();
const ampm = hours >= 12 ? 'pm' : 'am';
// converts hours to 12 hour instead of 24 hour
hours = hours % 12;
// converts 0 (midnight) to 12
hours = hours ? hours : 12; // the hour '0' should be '12'
// converts minutes to have leading 0
minutes = minutes < 10 ? '0' + minutes : minutes;
// converts minutes to have leading 0
days = days < 10 ? '0' + days : days;
month = month < 10 ? '0' + month : month;
// the time string
const time = hours + ':' + minutes + ' ' + ampm;
//the result
return `${days}/${month}/${year} ${time}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment