Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Author: Gerardo Junior <me@gerardo-junior.com
// Date: 10/14/2019, 8:53:55 PM
// URL: https://gist.github.com/gerardo-junior/ba6ab5a121248328005c5e53d00e7bd7
class DateFomater {
constructor(datetime) {
if (typeof datetime !== 'string')
throw new Error('The class parameter must be a String')
let datetimeArr = /(\d{2})\:(\d{2})\:(\d{2})\s(\d{2})\/(\d{2})\/(\d{4})/gi.exec(datetime)
if (!Array.isArray(datetimeArr))
throw new Error('The class parameter must be a date with HH:mm:ss DD/MM/YYYY format')
let datetimeObj = new Date(datetimeArr[6], datetimeArr[5]-1, datetimeArr[4], datetimeArr[1], datetimeArr[2], datetimeArr[3])
if (datetimeObj.getFullYear() !== parseInt(datetimeArr[6])
|| datetimeObj.getMonth()+1 !== parseInt(datetimeArr[5])
|| datetimeObj.getDay()+1 !== parseInt(datetimeArr[4])
|| datetimeObj.getHours() !== parseInt(datetimeArr[1])
|| datetimeObj.getMinutes() !== parseInt(datetimeArr[2])
|| datetimeObj.getSeconds() !== parseInt(datetimeArr[3]))
throw new Error('The class parameter must be a valid date')
this.datetime = datetimeObj;
}
get_unix() {
return Math.round(this.datetime.getTime() / 1000)
}
get_datetime() {
return this.datetime.toISOString().replace(/T/, ' ').replace(/\..+/, '')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment