如何使用javascript从1-366计算一年中的某一天?例如:
在OP的编辑之后:
var now = new Date(); var start = new Date(now.getFullYear(), 0, 0); var diff = now - start; var oneDay = 1000 * 60 * 60 * 24; var day = Math.floor(diff / oneDay); console.log('Day of year: ' + day);
编辑:上面的代码会失败时,now是3月26日和10月29日之间的日期now的时间是凌晨1点之前(如零时59分59秒)。这是因为该代码未考虑夏令时。
now
var now = new Date(); var start = new Date(now.getFullYear(), 0, 0); var diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000); var oneDay = 1000 * 60 * 60 * 24; var day = Math.floor(diff / oneDay); console.log('Day of year: ' + day);