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

时间:2012-11-26 19:27:48

标签: javascript jquery date time

  

可能重复:
  Calculate last day of month in JavaScript
  What is the best way to determine the number of days in a month with JavaScript?

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

例如,11月应为:

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

2 个答案:

答案 0 :(得分:637)

非常简单,无需图书馆:

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世纪,因此:

new Date(14, 0, 1);

给出1914年1月1日。为避免这种情况,请创建一个Date,然后使用 setFullYear 设置其值:

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

答案 1 :(得分:16)

我用Datejs

修复了它

这是警告第一天:

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

这是最后一天:

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