Ham*_*ter 52 javascript datetime
我仍然把头包在这个图书馆周围,但是我没时间,所以我会跳到扰流板部分然后问.使用给定的,任意毫秒的时间值(就像您给出的那种.getTime()
),如何获得当前分钟,小时,日,星期,月,星期和特定毫秒的年份时间?
此外,如何检索给定月份的天数?关于闰年和其他事情,我应该知道什么?
Lek*_*eyn 87
变量名称应该是描述性的:
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();
Run Code Online (Sandbox Code Playgroud)
某个月的日子不会改变.在闰年,2月有29天.灵感来自http://www.javascriptkata.com/2007/05/24/how-to-know-if-its-a-leap-year/(感谢Peter Bailey!)
继续上一段代码:
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;
Run Code Online (Sandbox Code Playgroud)
没有直接的方法来获得一年的一周.有关该问题的答案,请参阅javascript中是否有方法使用年份和ISO周数创建日期对象?
这是另一种获取日期的方法
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)
Run Code Online (Sandbox Code Playgroud)
关于每月的天数,只需使用静态 switch 命令并检查,if (year % 4 == 0)
在这种情况下,二月将有 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"));
Run Code Online (Sandbox Code Playgroud)