Skip to content

Instantly share code, notes, and snippets.

@zisra
Last active March 21, 2023 23:40
Show Gist options
  • Save zisra/e2ee46f4d67caa24ea55b2e9c2b4974d to your computer and use it in GitHub Desktop.
Save zisra/e2ee46f4d67caa24ea55b2e9c2b4974d to your computer and use it in GitHub Desktop.
Parse date
import parseDate from './parseDate.js';
parseDate('1 minute'); // => 60000
parseDate('1 hour'); // => 3600000
parseDate('Not a date'); // => Error: Invalid format
/*
* Usage: count {unit}
* Units:
* s, second, seconds, sec
* m, minute, minutes, min
* h hour, hours
* d, day, days
* w, week, weeks
* mo, month, months
* y, year, years
*/
function match(){
const input = Array.from(arguments);
const checkOn = input[0];
const checksList = input.slice(1);
let isMatch = false;
checksList.forEach(check=>{
if(checkOn === check){
isMatch = true;
}
})
return isMatch;
}
export default (timeString) => {
const splitDate = timeString.split(' ');
if(splitDate.length !== 2) throw new Error('Invalid format');
const date = splitDate[0];
const dateFormat = splitDate[1];
let millisecondLength;
if(match(dateFormat, 'ms', 'millisecond', 'milliseconds')){
millisecondLength = 1;
} else if(match(dateFormat, 's', 'second', 'seconds', 'sec')){
millisecondLength = 1000;
} else if(match(dateFormat, 'm', 'minute', 'minutes', 'min')){
millisecondLength = 1000 * 60;
} else if(match(dateFormat, 'h', 'hour', 'hours')){
millisecondLength = 1000 * 60 * 60;
} else if(match(dateFormat, 'd', 'day', 'days')){
millisecondLength = 1000 * 60 * 60 * 24;
} else if(match(dateFormat, 'w', 'week', 'weeks')){
millisecondLength = 1000 * 60 * 60 * 24 * 7;
} else if(match(dateFormat, 'mo', 'month', 'months')){
millisecondLength = 1000 * 60 * 60 * 24 * 30;
} else if(match(dateFormat, 'y', 'year', 'years')){
millisecondLength = 1000 * 60 * 60 * 24 * 365;
} else {
throw new Error('Invalid format');
}
return millisecondLength * parseInt(date);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment