Last active
August 29, 2015 14:26
-
-
Save golbin/5e089e948e886b98c66a to your computer and use it in GitHub Desktop.
Get a date of this week with a name of a day
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Maybe it's better to make using inheritance from Date.