Created
June 24, 2019 19:22
-
-
Save VhMuzini/1c6dd50de65846c2ee6914922e90a38d to your computer and use it in GitHub Desktop.
Utility date tools
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
import { isDate } from 'moment'; | |
export class DateTools { | |
static getToday() { | |
return new Date(); | |
} | |
static getLast30DaysFromNow() { | |
const today = new Date(); | |
const date = new Date(); | |
date.setDate( today.getDate() - 30); | |
return date; | |
} | |
static getLast24HoursFromNow() { | |
const today = new Date(); | |
const date = new Date(); | |
date.setHours( today.getHours() - 24); | |
return date; | |
} | |
static toDateTimeLocalInputFormat(date: Date) { | |
if (!isDate(date)) { | |
return 'Not a Date'; | |
} | |
let formatedDate: string; | |
// Setting the date | |
formatedDate = date.getFullYear() + '-'; | |
formatedDate = formatedDate + ( date.getMonth() + 1 < 9 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1) ); | |
formatedDate = formatedDate + '-' + ( date.getDate() < 10 ? '0' + date.getDate() : date.getDate() ); | |
// Setting time | |
// formatedDate = formatedDate + 'T' + date.getHours() + ':'; | |
formatedDate = formatedDate + 'T' + ( date.getHours() < 9 ? '0' + date.getHours() : date.getHours() ) + ':'; | |
formatedDate = formatedDate + ( date.getMinutes() < 9 ? '0' + date.getMinutes() : date.getMinutes() ) + ':'; | |
formatedDate = formatedDate + ( date.getSeconds() < 9 ? '0' + date.getSeconds() : date.getSeconds() ); | |
return formatedDate; | |
} | |
static isValidDate(date: Date) { | |
return isDate(date); | |
} | |
static formatDateYYYYMMDD(date: Date, separator: string = '-') { | |
const year = date.getFullYear(); | |
const month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1); | |
const day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate() ); | |
return (year + separator + month + separator + day); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment