89

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?

Hamster
  • 2,962
  • 7
  • 27
  • 38
  • It's all explained in the spec. There is a section which describes the date methods, and even the abstract algorithms. – Šime Vidas Dec 09 '10 at 20:48

4 Answers4

155

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?

Community
  • 1
  • 1
Lekensteyn
  • 64,486
  • 22
  • 159
  • 192
  • 1
    The idea's right, I think the logic is a bit off though... maybe `year%400===0 || (year%4===0 && year%100!==0)`. – bobince Dec 09 '10 at 21:32
  • 1
    This approach is pretty straightforward, too http://www.javascriptkata.com/2007/05/24/how-to-know-if-its-a-leap-year/ – Peter Bailey Dec 09 '10 at 21:34
  • Thanks again bobince. I'm using the approach from Peter Bailey now. Great idea. I always forget about such possibilities. – Lekensteyn Dec 09 '10 at 21:39
  • whats result_from_Date_getTime and why didn't you just call getTime in your example – john k Aug 11 '23 at 19:21
37

Here is another method to get date

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)
Parth Jasani
  • 2,349
  • 1
  • 19
  • 26
  • 19
    You should ALWAYS take a local copy of the date before extracting values from it as there is a significant chance that each `newDate()` will be returning a slightly different date/time and you could end up with unexpected results. – Chris Walsh Jan 10 '19 at 09:43
5

Regarding number of days in month just use static switch command and check if (year % 4 == 0) in which case February will have 29 days.

Minute, hour, day etc:

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"));
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
  • To check for a leap year you must check `if (((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))`. This is the definition of the Gregorian calendar. – Gabriel Glenn May 29 '17 at 15:40
1

Additionally, how do I retrieve the number of days of a given month?

Aside from calculating it yourself (and consequently having to get leap years right), you can use a Date calculation to do it:

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

In general for timestamp/date calculations I'd recommend using the UTC-based methods of Date, like getUTCSeconds instead of getSeconds(), and Date.UTC to get a timestamp from a UTC date, rather than new Date(y, m), so you don't have to worry about the possibility of weird time discontinuities where timezone rules change.

bobince
  • 528,062
  • 107
  • 651
  • 834
  • UTC works even when the month goes past december (12 and up)? – Hamster Dec 09 '10 at 22:29
  • Yes, that works in UTC or local time. (Well, unless in local time there is a timezone change on 1st January, in which case local time could go wrong. I don't know of any locales where that has ever happened, but I've learned always to be suspicious of the weird stuff that local timezone rules can generate...) – bobince Dec 10 '10 at 00:39