Reputation: 42484
I have below code to get the current Monday based on the given date parameter. It works fine for most of time. But it doesn't work when it cross year. For example, if I pass new Date('2020-01-02T15:33:50Z')
as the parameter, it returns 2019-12-29T15:33:50.000Z
which is not correct. It should return 2019-12-30
. How can I make it work for cross year case?
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
return new Date(d.setDate(diff));
}
Upvotes: 3
Views: 174
Reputation: 311
You can change all the dates to timestamps and then subtract the difference.
function getMonday(d) {
const value = new Date(d)
const value_seconds = value.getTime() / 1000
const value_day = value.getDay()
let diff_seconds = 0 // default, expect value_day is monday
if(value_day > 1){ // if day is tuesday to saturday
const diff_day = value_day - 1
diff_seconds = diff_day * 24 * 3600 // find different in seconds
}
if(value_day === 0){ // if days is sunday
const diff_day = 6 // substract by 6 days, back to monday
diff_seconds = diff_day * 24 * 3600 // find different in seconds
}
const result_second = value_seconds - diff_seconds
const result = result_second * 1000
return new Date(result);
}
const today = new Date()
console.log(getMonday(today))
console.log(getMonday(today).getDay())
const issuedDate = new Date('2020-01-02T15:33:50Z')
console.log(getMonday(issuedDate))
console.log(getMonday(issuedDate).getDay())
Upvotes: 1
Reputation: 820
My idea in this regard is that if there is such a problem with cross years, then you can try to start from the raw format in which the date is presented, namely the number of milliseconds since 1970, and operate with this number to find Monday. For example like this:
let currentDate = new Date();
get current date
let currentDateMs = currentDate.getTime();
get current date in milliseconds
let dayNumber = (currentDate.getDay() + 6) % 7;
in Date object the countdown of days in the week starts from Sunday, so we shift it so that it starts from Monday
let result = currentDateMs - 86400000 * dayNumber;
subtract the number of milliseconds in a day (1000 * 3600 * 24 = 86400000) multiplied by the number of the current day (0-6) from the current date, and also because of this, we do not need to check if it is Monday, since the Monday number here is 0 and this will eliminate unnecessary subtraction
let resultDate = new Date(result);
console.log(resultDate.toDateString());
Upvotes: 1