Skip to content

Instantly share code, notes, and snippets.

@hawkeye64
Created June 1, 2019 17:29
Show Gist options
  • Save hawkeye64/31a9e731b293c2d04c1d10453d922db6 to your computer and use it in GitHub Desktop.
Save hawkeye64/31a9e731b293c2d04c1d10453d922db6 to your computer and use it in GitHub Desktop.
Date/Time Parser (javascript)
const parse = (input: string, format: string, key: string): string => {
const index = format.indexOf(key);
return input.slice(index, index + key.length);
};
export const dateParse = (input: string, format: string = 'YYYY-MM-DD HH.mm.ss', { epoch = 2000 } = {}): Date => {
let year = 2000;
if (format.includes('YYYY')) {
year = parseInt(parse(input, format, 'YYYY'), 10);
} else if (input.includes('YY')) {
year = parseInt(parse(input, format, 'YY'), 10) + epoch;
}
let month = 0;
if (format.includes('MM')) {
month = parseInt(parse(input, format, 'MM'), 10) - 1;
}
let date = 1;
if (format.includes('DD')) {
date = parseInt(parse(input, format, 'DD'), 10);
}
let hours = 0;
if (format.includes('HH')) {
hours = parseInt(parse(input, format, 'HH'), 10);
}
let minutes = 0;
if (format.includes('mm')) {
minutes = parseInt(parse(input, format, 'mm'), 10);
}
let seconds = 0;
if (format.includes('ss')) {
seconds = parseInt(parse(input, format, 'ss'), 10);
}
return new Date(year, month, date, hours, minutes, seconds);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment