使用 JavaScript 或 jQuery 获取当月的第一个和最后一个日期
问题描述:
正如标题所说,我一直在寻找一种方法来使用 JavaScript 或 jQuery 获取当月的第一个和最后一个日期,并将其格式化为:
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:
例如,对于 11 月,它应该是:
For example, for November it should be :
var firstdate = '11/01/2012';
var lastdate = '11/30/2012';
答
非常简单,不需要库:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
或者你可能更喜欢:
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);
编辑
某些浏览器会将两位数的年份视为 20 世纪,因此:
EDIT
Some browsers will treat two digit years as being in the 20th century, so that:
new Date(14, 0, 1);
给出 1914 年 1 月 1 日.为了避免这种情况,创建一个 Date 然后使用 setFullYear 设置它的值:
gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:
var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14