2010-12-09 60 views
35

我仍然环绕着这个图书馆,但我没有时间,所以我会只需跳到扰流板部分并询问。使用给定的毫秒毫秒时间值(例如您从.getTime()得到的类型),我如何获得特定毫秒的当前分,小时,星期,月,月,星期和年时间?Javascript,时间和日期:获取给定毫秒时间的当前分钟,小时,星期,星期,月份,年份

此外,如何检索给定月份的天数?任何我应该知道的关于闰年和其他东西的事情?

+0

它在规范的所有解释。有一节介绍日期方法,甚至是抽象算法。 – 2010-12-09 20:48:20

回答

58

变量名应该是描述:

var date = new Date; 
date.setTime(result_from_Date_getTime); 

var seconds = date.getSeconds(); 
var minutes = date.getMinutes(); 
var hour = date.getHours(); 

var year = date.getFullYear(); 
var month = date.getMonth(); // beware: January = 0; February = 1, etc. 
var day = date.getDate(); 

var dayOfWeek = date.getDay(); // Sunday = 0, Monday = 1, etc. 
var milliSeconds = date.getMilliseconds(); 

某一个月的日子不会改变。在闰年中,2月有29天。灵感来自http://www.javascriptkata.com/2007/05/24/how-to-know-if-its-a-leap-year/(感谢彼得·贝利!)

从以前的代码续:

var days_in_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; 
// for leap years, February has 29 days. Check whether 
// February, the 29th exists for the given year 
if((new Date(year, 1, 29)).getDate() == 29) days_in_month[1] = 29; 

有没有简单的方法来获得一年的一周。有关该问题的答案,请参阅Is there a way in javascript to create a date object using year & ISO week number?

+0

这不是确定闰年的完整算法。 – bobince 2010-12-09 21:16:37

+0

查看维基百科后编辑它。感谢您的注意。 – Lekensteyn 2010-12-09 21:29:24

+0

这个想法是正确的,我认为逻辑是有点关闭,虽然...也许`year%400 === 0 || (年%4 === 0 && year%100!== 0)`。 – bobince 2010-12-09 21:32:40

3

关于月中的天数,只需使用静态切换命令并检查if (year % 4 == 0),在这种情况下,2月将有29天。

分钟,小时,天等:

var someMillisecondValue = 511111222127; 
var date = new Date(someMillisecondValue); 
var minute = date.getMinutes(); 
var hour = date.getHours(); 
var day = date.getDate(); 
var month = date.getMonth(); 
var year = date.getFullYear(); 
alert([minute, hour, day, month, year].join("\n")); 
1

此外,我该如何找回某个月份的天数?

var y= 2010, m= 11;   // December 2010 - trap: months are 0-based in JS 

var next= Date.UTC(y, m+1); // timestamp of beginning of following month 
var end= new Date(next-1);  // date for last second of this month 
var lastday= end.getUTCDate(); // 31 

一般的时间戳/日期计算,我建议:

从自己计算它(并因此不必获得闰年右),您可以使用日期计算做

除了使用基于UTC的Date方法,如getUTCSeconds而不是getSeconds()Date.UTC从UTC日期获取时间戳,而不是new Date(y, m),因此您不必担心时区规则更改时发生奇怪时间不连续的可能性。

3

这里是另一种方法来获取日期

new Date().getDate()   // Get the day as a number (1-31) 
new Date().getDay()   // Get the weekday as a number (0-6) 
new Date().getFullYear()  // Get the four digit year (yyyy) 
new Date().getHours()   // Get the hour (0-23) 
new Date().getMilliseconds() // Get the milliseconds (0-999) 
new Date().getMinutes()  // Get the minutes (0-59) 
new Date().getMonth()   // Get the month (0-11) 
new Date().getSeconds()  // Get the seconds (0-59) 
new Date().getTime()   // Get the time (milliseconds since January 1, 1970) 
相关问题