I am trying to get the week number of current date / specific date falls in. Any suggestions for logic building will be helpful.
-
Have a look on that maybe : stackoverflow.com/questions/9045868/javascript-date-getweekR. Foubert– R. Foubert2016-07-11 13:36:32 +00:00Commented Jul 11, 2016 at 13:36
-
May check out moment if you want to work with dates in JS.Lux– Lux2016-07-11 13:36:38 +00:00Commented Jul 11, 2016 at 13:36
-
Do you want to get an ISO standard week number, or some localized week number?Teemu– Teemu2016-07-11 13:37:24 +00:00Commented Jul 11, 2016 at 13:37
Add a comment
|
2 Answers
function getWeekNumber(thisDate) {
var dt = new Date(thisDate);
var thisDay = dt.getDate();
var newDate = dt;
newDate.setDate(1); // first day of month
var digit = newDate.getDay();
var Q = (thisDay + digit) / 7;
var R = (thisDay + digit) % 7;
if (R !== 0) return Math.ceil(Q);
else return Q;}
getWeekNumber("07/31/2016");
1 Comment
RobG
You should not parse strings using the Date constructor (or Date.parse, they are equivalent for parsing). It does not make sense to use Date methods to create a string to then parse to another Date (e.g. to get the first of the month), just use Date methods directly:
newDate.setDate(1).let _ = new Date,
__ = ~~((new Date(_.getFullYear(), 0, 0) - _) / 36e5 * 24),
___ = (__ - __ % 7) / 7;
1 Comment
dakab
Care for additional explanation (like why you're using underscores instead of names)?