如何在javascript中获得第一天和最后一天

时间:2016-06-02 05:15:00

标签: javascript dayofweek

需要获得一年中的第一天和最后一天仅通过年份数。它几乎就像下面一样。

var year = 2016 //Any Year
var first_day = ? //From Year
var last_day = ? //From Year

示例:

// Fist day is Thursday and last day of that year is Sunday.

4 个答案:

答案 0 :(得分:5)

var year = 2016 //Any Year
var first_date = new Date(year, 0, 1);
var last_date = new Date(year, 11, 31);

document.write(first_date);
document.write("<br/>");
document.write(last_date);

答案 1 :(得分:1)

使用 Date() 方法生成,使用有效的日期字符串

var year = 2016 //Any Year
var first_date = new Date('1 January ' + 2016 + ' 00:00:00') //From Year
var last_date = new Date('31 December ' + 2016 + ' 00:00:00') //From Year

document.write(first_date + '<br>' + last_date)

或者像new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);格式

这样的参数

var year = 2016 //Any Year
var first_date = new Date(2016 ,0,1) //From Year
var last_date = new Date(2016,11,31) //From Year

document.write(first_date + '<br>' + last_date)

答案 2 :(得分:1)

你想要这样吗?

var year = 2016 //Any Year
var first_date = new Date(year,0,1)
var last_date = new Date(year,11,31)

答案 3 :(得分:0)

最新版本的ECMA脚本提供按语言环境显示工作日的功能,并且在所有最新的浏览器和NodeJS中均受支持:

var year = 2016 //Any Year
var first_day = new Date(year, 0, 1).toLocaleString('en-us', {  weekday: 'long' });
var last_day = new Date(year, 11, 31).toLocaleString('en-us', {  weekday: 'long' });

document.write("First Day => "+first_day);
document.write("<br/>");
document.write("Last Day => "+last_day);