Javascript - Date

JavaScript

http://www.datejs.com/

Important:
http://www.hunlock.com/blogs/Javascript_Dates-The_Complete_Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

https://www.sitepoint.com/beginners-guide-to-javascript-date-and-time/ - done reading
https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/ - done reading

http://www.htmlgoodies.com/html5/javascript/calculating-the-difference-between-two-dates-in-javascript.html
http://www.htmlgoodies.com/html5/javascript/learn-how-to-use-javascript-dates-and-leap-years.html
http://en.wikipedia.org/wiki/Leap_year

Date Duration Calculator:
http://www.timeanddate.com/date/duration.html

Relative data and time:
https://github.com/azer/relative-date
http://www.eahanson.com/2008/12/04/relative-dates-in-javascript/
http://momentjs.com/
http://www.datejs.com/
http://timeago.yarp.com/
http://ejohn.org/blog/javascript-pretty-date/
http://37signals.com/svn/posts/1557-javascript-makes-relative-times-compatible-with-caching
http://easydate.parshap.com/
http://wiki.processmaker.com/index.php/2.0/Dates
http://twitter.pbworks.com/w/page/1779897/RelativeTimeScripts
http://www.ashbykuhlman.net/blog/2002/12/19/2341
http://nodemanual.org/latest/js_doc/Date.html
http://www.snippetsmania.com/javascript-parse-relative-date/
http://closure-library.googlecode.com/svn/docs/closure_goog_date_relative.js.html

// JavaScript - Date

getMilliseconds method which returns a number between 0 and 999. This is not 
unique enough if you intend to use it to generate unique URL to avoid browser 
caching issue. Consider using the valueOf method, or the getTime() method:

url = url + '&ts=' + (new Date()).getTime();

On the Java side, we need to send appropriate cache control headers:

response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.setHeader("Expires", "Thu, 01 Jan 1970 00:00:00 GMT");
response.setHeader("Pragma", "no-cache");

var now = (new Date()).toLocaleDateString(); // 2/13/2017

var d = new Date();  // Now
var d = new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
var d = new Date('January 16, 1988'); // Midnight of January 16th, 1988
var d = new Date('January 16, 1988 2:54:16 pm GMT');

JavaScript Date objects can only be instantiated by calling JavaScript Date as 
a constructor: calling it as a regular function (i.e. without the new operator) 
will return a string rather than a Date object; unlike other JavaScript object 
types, JavaScript Date objects have no literal syntax.

Where Date is called as a constructor with more than one argument, if values are 
greater than their logical range (e.g. 13 is provided as the month value or 70 
for the minute value), the adjacent value will be adjusted. For example:
new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), 
both create a date for 2014-02-01 (note that the month is 0-based). Similarly 
for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new 
Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

Where Date is called as a constructor with more than one argument, the specifed 
arguments represent local time. If UTC is desired, use new Date(Date.UTC(…)) 
with the same arguments.

// To parse a date, just construct the date object from the string:
var d = new Date('January 16, 1988'); // Midnight of January 16th, 1988
var d = new Date('January 16, 1988 2:54:16 pm GMT');

In JavaScript, months go from 0 to 11. January is 0.

JavaScript has a little quirk where a date of zero will set the date to be the 
last day of the previous month. Likewise, if there are 30 days in a month and 
you set a date of 31, it will be the first day of the next month.

JavaScript dates are like other JavaScript objects. They are passed by reference. 
When you pass a date object to a function, the date object is passed by reference. 
If your function make any changes to the date object, it effects the original 
date object as well.

avaScript dates are assigned by references. When you assign an existing date 
object to a variable, you are assigning a pointer to the original date object 
(or variable hold a reference to the original date object). Anything you do to 
the new variable affects the original date object.

UTC, or Coordinated Universal Time, is for all intended purpose, Greenwich 
Mean Time, or the timezone of Greenwich, England. EST is -5 hours from GMT. 
CST (central US) is -6 from GMT. MST (Mountain Time) is -7 hours and PST is -8 
hours. These numbers can vary by as much as an hour depending on whether or not 
Daylight Savings Time is in effect or not.

When you create a new date without specifying a time zone, JavaScript will 
create the date using the browser's time zone. When you output the date, 
unless you specifically use the UTC date methods, the date will be converted to 
user's local time zone regardless of how it was created.

var unixTimestamp = Date.now(); // in milliseconds
(new Date()).getFullYear();

Date.now() // the number of milliseconds elapsed since 1 January 1970 00:00:00 
           // UTC, with leap seconds ignored.
date1 = new Date ( "January 6, 2013" );
.toDateString()
.toISOString()
.toGMTString() // deprecated
.toLocaleDateString()
.toLocaleFormat() // converts a date to a string, using a format string
  // (not standardized yet)
.toLocaleString()
.toLocaleTimeString()
date1.getFullYear(); // returns four-digit year
date1.getYear(); // returns two-digit year
date1.getDate(); // Day of the month (1-31).
date1.getMonth(); // the month (0-11)
.getDay() // day of the week (0-6)
.getHours() // the hour (0-23)
.getMilliseconds() // Returns the milliseconds (0-999) 
.getMinutes() // the minutes (0-59)
.getSeconds(); // returns the seconds (0-59)
.getTime() // returns number of milliseconds since January 1, 1970, 00:00:00 UTC
  // (negative for prior times).
.getTimezoneOffset() // returns the time-zone offset in minutes for the 
  // current locale.
.getUTCDate() // the day (date) of the month (1-31) in UTC

date1 = new Date ();
date1.setDate(20);

To format a date using moment.js:
var dateObj = new Date();
var dateString = moment(dateObj).format('YYYYDDD');

You are allowed to use numbers which don’t fall into the above ranges, 
to generate future or past dates. 
date1 = new Date ();
date1.setDate(-1);
date1.setMonth(-1);
Assume that current date is February 20th, 2013. The above code will change to 
the second to last date of the previous month in the previous year, which would 
be December 30th, 2012. Similarly, you can use values greater than 31 for date 
and 11 for month to generate future dates. Having learned how to use Date object 
to generate dates using various methods, let’s see how we can format dates.

// Comparing date objects:
if(date1.getTime() == date2.getTime()){
  console.log("Dates are equal");
}

var date1=new Date();
date1.setHours(0,0,0,0);
var date2=new Date("2013-02-18");

So, date1 will be something like Mon Feb 18 2013 00:00:00 GMT+0530 (IST). But, 
it still doesn’t match since date2 will contain the time in your local time zone, 
which is GMT+5.30 for me. If you don’t want to consider the time, the best way 
is to set both dates into the same time, as shown below.

var date1=new Date();
date1.setHours(0,0,0,0);
var date2=new Date("2013-02-17");
date2.setHours(0,0,0,0);

We can use same technique for comparing date ranges as well. Make sure to set 
all the other components of both dates to the same value and only check for the 
components which vary across both dates.

Should I use getMilliseconds if I need a timestamp

getMilliseconds method which returns a number between 0 and 999. This is not unique enough if you intend to use it to generate unique URL to avoid browser caching issue. Consider using the valueOf method, or the getTime() method:

+ '&ts=' + (new Date()).getTime()

On the Java side, we need to send appropriate cache control headers:

response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.setHeader("Expires", "Thu, 01 Jan 1970 00:00:00 GMT");
response.setHeader("Pragma", "no-cache");

How can we create a date object?

var d = new Date();  // Because we did not specify a date or time, the date will be equal to the instant it was created
var d = new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
var d = new Date('January 16, 1988'); // Midnight of January 16th, 1988
var d = new Date('January 16, 1988 2:54:16 pm GMT');

JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the new operator) will return a string rather than a Date object; unlike other JavaScript object types, JavaScript Date objects have no literal syntax.

Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(Date.UTC(…)) with the same arguments.

How can we parse a date?

var d = new Date('January 16, 1988'); // Midnight of January 16th, 1988
var d = new Date('January 16, 1988 2:54:16 pm GMT');

In JavaScript, what value represent January and what value represent December?

In JavaScript, months go from 0 to 11. January is 0.

When you specify a date of 0, how does JavaScript behave?

JavaScript has a little quirk where a date of zero will set the date to be the last day of the previous month. Likewise, if there are 30 days in a month and you set a date of 31, it will be the first day of the next month.

Are date objects passed by value or passed by reference?

JavaScript dates are like other JavaScript objects. They are passed by reference. When you pass a date object to a function, the date object is passed by reference. If your function make any changes to the date object, it effects the original date object as well.

What happens when we assign a date object to a variable?

JavaScript dates are assigned by references. When you assign an existing date object to a variable, you are assigning a pointer to the original date object (or variable hold a reference to the original date object). Anything you do to the new variable affects the original date object.

What is UTC?

UTC, or Coordinated Universal Time, is for all intended purpose, Greenwich Mean Time, or the timezone of Greenwich, England. EST is -5 hours from GMT. CST (central US) is -6 from GMT. MST (Mountain Time) is -7 hours and PST is -8 hours. These numbers can vary by as much as an hour depending on whether or not Daylight Savings Time is in effect or not.

What happen when you create a new date object without specifying the timezone?

When you create a new date without specifying a time zone, JavaScript will create the date using the browser's time zone. When you output the date, unless you specifically use the UTC date methods, the date will be converted to user's local time zone regardless of how it was created.

How can we obtain the unix timestamp of a date object?

var unixTimestamp = Date.now(); // in milliseconds

How can we get the current year?

(new Date()).getFullYear()

How can we format a date object as string?

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
  3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
  4. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toTimeString
  5. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString
  6. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString
  7. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toGMTString
  8. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
  9. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat
  10. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
  11. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString
  12. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat

Use something like moment.js or https://github.com/samsonjs/strftime

var dateObj = new Date();
var dateString = moment(dateObj).format('YYYYDDD');
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License