Javascript 如何在javascript中获得当年的第一天?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14434777/
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
How to get first day of current year in javascript?
提问by user1990525
I need javascript code to get first day of year. e.g. It will be 1st Jan 2013 for this year.
我需要 javascript 代码才能获得一年的第一天。例如,今年将是 2013 年 1 月 1 日。
For next year it should be 1st Jan 2014. So basically 1st day of whatever is current year.
明年应该是 2014 年 1 月 1 日。所以基本上是今年的第一天。
回答by Guffa
Create a new Dateinstance to get the current date, use getFullYearto get the year from that, and create a Dateintance with the year, month 0 (January), and date 1:
创建一个新Date实例以获取当前日期,用于getFullYear从中获取年份,并创建一个Date包含年份、月份 0(一月)和日期 1的实例:
var d = new Date(new Date().getFullYear(), 0, 1);
回答by Moritz Roessler
var year = 2013;
var date = new Date(year, 0, 1);
console.log(date); // Tue Jan 01 2013 00:00:00 GMT+0100 (Mitteleurop?ische Zeit)
You can construct Dates using new Date(YEAR,MONTH,DAY)
您可以使用构造日期 new Date(YEAR,MONTH,DAY)
So giving the constructor the yearyou want and the first Day of the First Month, you get your Date Object
所以给构造函数year你想要的和第一个月的第一天,你得到你的日期对象
Note that the Date Object starts counting with 0 for the Month, so January == 0
请注意,日期对象从 0 开始计算月份,因此一月 == 0
回答by Nick
Try this one:
试试这个:
var timestmp = new Date().setFullYear(new Date().getFullYear(), 0, 1);
var yearFirstDay = Math.floor(timestmp / 86400000);
var day = new Date(yearFirstDay);
alert(day.getDay());
Note: that code returns number, so Sunday is 0, Monday is 1, and so on.
注意:该代码返回数字,因此星期日为 0,星期一为 1,依此类推。
回答by Nick
var d = new Date(2013, 0, 1).getDay(); //0 is January for some reason
alert(d);

