使用 JavaScript 或 jQuery 获取当月的第一个和最后一个日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13571700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:23:14  来源:igfitidea点击:

Get first and last date of current month with JavaScript or jQuery

javascriptjquerydatetime

提问by Moozy

As title says, I'm stuck on finding a way to get the first and last date of the current month with JavaScript or jQuery, and format it as:

正如标题所说,我一直在寻找一种方法来使用 JavaScript 或 jQuery 获取当月的第一个和最后一个日期,并将其格式化为:

For example, for November it should be :

例如,对于 11 月,它应该是:

var firstdate = '11/01/2012';
var lastdate = '11/30/2012';

回答by RobG

Very simple, no library required:

非常简单,不需要库:

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

or you might prefer:

或者您可能更喜欢:

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);

EDIT

编辑

Some browsers will treat two digit years as being in the 20th century, so that:

一些浏览器会将两位数的年份视为 20 世纪,因此:

new Date(14, 0, 1);

gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:

给出 1 January, 1914. 为了避免这种情况,创建一个 Date 然后使用setFullYear设置它的值:

var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14

回答by Moozy

I fixed it with Datejs

我用 Datejs

This is alerting the first day:

这是第一天的警报:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

这是最后一天:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);