Skip to content

Instantly share code, notes, and snippets.

@tincho
Last active July 13, 2022 04:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tincho/4fbd9422d7ae5f7fc8160028add515a8 to your computer and use it in GitHub Desktop.
Save tincho/4fbd9422d7ae5f7fc8160028add515a8 to your computer and use it in GitHub Desktop.
some utils for JS Date handling
/*
why fixDate?
if we create a JS Date writing:
var d = new Date("2015-05-15")
we are not specifying any timezone
the browser/environment will asume it is UTC+000,
and always represent it in user's LOCAL TIMEZONE!
so, running in an environment located in a UTC-3 zone,
d would actually show 2015-05-14 at 21:00
and may lead to errors.
fixDate fixes a date without specified timezone offset, and forces the current user env timezone offset
*/
const fixDate = date => {
let d = date;
d.setMinutes(d.getMinutes() + d.getTimezoneOffset());
return d;
};
const strToDate = str => fixDate(new Date(str));
const dateToStr = date => date.toISOString().slice(0, 10);
const dateToArr = date => date.match(/(\d{4})-(\d{1,2})-(\d{1,2})/, false).slice(1);
function datesBetween(...dates) {
// handle both:
// datesBetween( "2017-06-06", "2017-06-09")
// datesBetween(["2017-06-06", "2017-06-09"])
if (typeof dates[0] != 'string' && dates[0].length > 1) {
dates = dates[0];
}
let [begin, end] = dates.map(strToDate);
dates.pop(); // remove end date to avoid repetition
let next = begin;
for (let i = 1; next < end; i++) {
// setDate handles
next.setDate(next.getDate() + 1);
dates.splice(i, 0, dateToStr(next))
}
return dates;
}
// Date.prototype.getDay returns 0 for sunday, 1 monday .... 6 = saturday
const isWeekend = date => [0, 6].includes(strToDate(date).getDay());
const isWorkDay = date => !isWeekend(date); // && !isHoliday(date)
const workDaysBetween = (...dates) => datesBetween(dates).filter(isWorkDay);
// workDaysBetween( "2017-06-01", "2017-06-30" ) will return array of all monday to friday days including 01 and 30
@tincho
Copy link
Author

tincho commented Jul 13, 2022

little context: this was part of a Browse-console hack to a time-tracking app of the company where I worked back then.

At the end of the month I just generated the array of "workable days" (manually removing any holiday, etc) and feed them to another script that made all the submissions for such days :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment