本文介绍了如何在JavaScript中获取本周的第一个和最后一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 today = new Date();
对象。我需要得到本周的第一天和最后一天。我需要星期天和星期一的两个变体作为一周的开始和结束的一天。我现在有点混淆一个代码。你可以帮我吗?
I have today = new Date();
object. I need to get first and last day of the current week. I need both variants for Sunday and Monday as a start and end day of the week. I am little bit confuse now with a code. Can your help me?
推荐答案
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
firstday
"Sun, 06 Mar 2011 12:25:40 GMT"
lastday
"Sat, 12 Mar 2011 12:25:40 GMT"
这适用于本周的第一天=星期天,也是最后一天=本周的星期六。扩展它运行星期一到星期日是微不足道的。
This works for firstday = sunday of this week and last day = saturday for this week. Extending it to run Monday to sunday is trivial.
使其在不同月份的头一天和最后几天工作留给用户一个练习
Making it work with first and last days in different months is left as an exercise for the user
这篇关于如何在JavaScript中获取本周的第一个和最后一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!