Javascript,时间和日期:获取给定毫秒时间的当前分钟,小时,日,周,月,年 [英] Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time

查看:239
本文介绍了Javascript,时间和日期:获取给定毫秒时间的当前分钟,小时,日,周,月,年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还在围绕这个图书馆,但是我没有时间,所以我只是跳到扰流板部分,问。有一个给定的,任意毫秒的时间值(像你从 .getTime())中提供的那种,我如何获得当前的分钟,小时,日,周月,月,年以及特定毫秒级的年份?



此外,如何检索给定月份的天数? / p>

解决方案

变量名应该是描述性的:

  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?

这篇关于Javascript,时间和日期:获取给定毫秒时间的当前分钟,小时,日,周,月,年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆