Skip to content

Instantly share code, notes, and snippets.

@golbin
Last active August 29, 2015 14:26
Show Gist options
  • Save golbin/5e089e948e886b98c66a to your computer and use it in GitHub Desktop.
Save golbin/5e089e948e886b98c66a to your computer and use it in GitHub Desktop.
Get a date of this week with a name of a day
function MyDate (args) {
var MICROSECONDS_OF_A_DAY = 86400000,
today = args ? new Date(args) : new Date(),
daysOfThisSunday = Math.floor(today.getTime() / MICROSECONDS_OF_A_DAY) - today.getDay();
var dayNames = {
SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6
};
return {
/**
* @param {Number|String} day A name of a day OR 0(Sunday),1,2,3,4,5,6
* @return {Date}
*/
getDate: function (day) {
if (typeof day === 'string') {
day = dayNames[day.slice(0,3).toUpperCase()];
}
return new Date((daysOfThisSunday + day) * MICROSECONDS_OF_A_DAY);
}
};
}
// With today
var myDate = new MyDate();
var thisMonday = myDate.getDate("MONDAY");
var thisFriday = myDate.getDate("friday");
var thisTuesday = myDate.getDate("TUE");
var thisSaturday = myDate.getDate(6);
// With a specific day
var myDate2 = new MyDate("1978-07-29");
var theMonday = myDate2.getDate("MONDAY");
var theFriday = myDate2.getDate("FRIDAY");
@golbin
Copy link
Author

golbin commented Aug 7, 2015

Maybe it's better to make using inheritance from Date.

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