如何在 JavaScript 中获取本周的第一天和最后一天 [英] How to get first and last day of the current week in JavaScript

查看:80
本文介绍了如何在 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 中获取本周的第一天和最后一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆