Javascript,时间和日期:获取给定毫秒时间的当前分钟,小时,日,周,月,年

时间:2010-12-09 20:45:40

标签: javascript datetime

我仍然把头包在这个图书馆周围,但是我已经没时间了,所以我会跳到扰流板部分问一下。使用给定的任意毫秒时间值(就像您从.getTime()提供的那种),如何获得当前分钟,小时,日,星期,月,星期和星期那个特定的毫秒时间?

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

4 个答案:

答案 0 :(得分:84)

变量名称应该是描述性的:

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/(感谢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;

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

答案 1 :(得分:7)

这是获取日期的另一种方法

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)

答案 2 :(得分:3)

关于月中的天数,只需使用静态切换命令并检查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"));

答案 3 :(得分: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),所以你不必担心时区规则发生变化的奇怪时间不连续的可能性。

相关问题