Skip to content

Instantly share code, notes, and snippets.

@leonardorifeli
Last active October 19, 2020 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonardorifeli/d14dc4ce69419248b5d36f6318e1a64c to your computer and use it in GitHub Desktop.
Save leonardorifeli/d14dc4ce69419248b5d36f6318e1a64c to your computer and use it in GitHub Desktop.
Date Parser with typescript
class DateParser {
date: Date;
constructor(date: string) {
try {
this.date = new Date(this.format(date));
} catch (e) {
throw e;
}
}
getUnix() {
return this.date.getTime() / 1000;
}
getDateTime() {
return this.date.toUTCString();
}
private format(date: string) {
let formatted = date.split(' ');
if(formatted.length == 0)
throw new Error('Date is invalid.');
let onlyTime = formatted[0].split(':');
let onlyDate = formatted[1].split('/');
if(onlyDate.length != 3 || onlyTime.length != 3)
throw new Error('Invalid date or time. Plase check and use the HH:mm:ss DD/MM/YYYY format');
return Date.UTC(parseInt(onlyDate[2]), parseInt(onlyDate[1]), parseInt(onlyDate[0]), parseInt(onlyTime[0]), parseInt(onlyTime[1]), parseInt(onlyTime[2]));
}
}
try {
let date = new DateParser("23:30:00 18/10/2020");
console.log('getDateTime:', date.getDateTime());
console.log('getUnix:', date.getUnix());
} catch (e) {
console.error('Error to use date.', e.message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment