Last active
May 11, 2022 14:48
-
-
Save sktwentysix/b4a8017785309b2534da2fa5e2ef4b02 to your computer and use it in GitHub Desktop.
Javascript DateTime Functions
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
function getYearMonthDay(isoDateTime) { | |
const year = date.getFullYear() | |
const month = (date.getMonth() + 1 < 10 ? '0' : '') + (date.getMonth() + 1) | |
const day = date.getDate(); | |
return year + '/' + month + '/' + day | |
} | |
function getDayMonthYear(isoDateTime) { | |
const year = date.getFullYear() | |
const month = (date.getMonth() + 1 < 10 ? '0' : '') + (date.getMonth() + 1) | |
const day = date.getDate(); | |
return day + '/' + month + '/' + year | |
} | |
function getYearMonthDayWithHyphens(isoDateTime) { | |
const year = date.getFullYear() | |
const month = (date.getMonth() + 1 < 10 ? '0' : '') + (date.getMonth() + 1) | |
const day = date.getDate(); | |
return year + '-' + month + '-' + day | |
} | |
function getOrdinalDate(isoDateTime: Date) { | |
const date = isoDateTime.getDate(); | |
if (date == 11 || date == 12 || date == 13) return date + 'th' | |
switch (date % 10) { | |
case 1: return date + 'st' | |
case 2: return date + 'nd' | |
case 3: return date + 'rd' | |
default: return date + 'th' | |
} | |
} | |
function getDayName(isoDateTime: Date) { | |
const days = [ | |
"Sunday", | |
"Monday", | |
"Tuesday", | |
"Wednesday", | |
"Thursday", | |
"Friday", | |
"Saturday" | |
] | |
return days[isoDateTime.getDay()] | |
} | |
function getMonthName(isoDateTime: Date) { | |
const months = [ | |
"January", | |
"February", | |
"March", | |
"April", | |
"May", | |
"June", | |
"July", | |
"August", | |
"September", | |
"October", | |
"November", | |
"December" | |
]; | |
return months[isoDateTime.getMonth()] | |
} | |
function numberOfDaysBetweenNowAndAnother(isoDateTime: Date) { | |
const currentDate = new Date().getTime(); | |
const destinationDate = isoDateTime.getTime(); | |
const numberOfSecondsBetweenDates = | |
Math.abs(destinationDate - currentDate) | |
const numberOfDaysBetweenDates = | |
numberOfSecondsBetweenDates / (1000 * 3600 * 24) | |
return Math.round(numberOfDaysBetweenDates * 10) / 10 | |
} | |
function getTwelveHourTime(isoDateTime: Date) { | |
let hour = isoDateTime.getHours(); | |
const minutes = isoDateTime.getMinutes(); | |
const meridiem = (hour < 12) ? 'am' : 'pm' | |
if (hour > 12) hour = hour - 12 | |
else if (hour == 0) hour = 12 | |
return hour + ':' + minutes + meridiem | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment