且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-13 14:44:38

变量名应该是描述性的:

  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(); //请注意:1月= 0; 2月= 1等。
var day = date.getDate();

var dayOfWeek = date.getDay(); //星期日= 0,星期一= 1等。
var milliSeconds = date.getMilliseconds();

给定月份的日子不会改变。在闰年,二月有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]; 
//闰年,二月有29天。检查
// 2月29日是否在给定年份存在
if((new Date(year,1,29))。getDate()== 29)days_in_month [1] = 29;

没有一个简单的方式来获得一年的这个星期。有关该问题的答案,请参阅有没有办法在javascript中创建一个日期对象,使用年份& ISO周号?


I'm still wrapping my head around this library, but I'm out of time so I'll just skip to the spoiler section and ask. With a given, arbitrary millisecond time value (like the kind you'd gave from .getTime()), how do I get the current minute, hour, day, week of the month, month, week of the year, and year of that specific millisecond of time?

Additionally, how do I retrieve the number of days of a given month? Anything I should know about regarding leap years and other stuff?

The variable names should be descriptive:

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();

The days of a given month do not change. In a leap year, February has 29 days. Inspired by http://www.javascriptkata.com/2007/05/24/how-to-know-if-its-a-leap-year/ (thanks Peter Bailey!)

Continued from the previous code:

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;

There is no straightforward way to get the week of a year. For the answer on that question, see Is there a way in javascript to create a date object using year & ISO week number?