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

查看:104
本文介绍了如何在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天全站免登陆