Javascript - Date

About

A date object to store date information.

The month is manipulated with January = 0 and not 1

Example

now = new Date();
console.log("We are the "+now.getDate()+"-"+(now.getMonth()+1)+"-"+now.getFullYear());
console.log("We are in String the "+now.toString());
console.log("We are in Date String the "+now.toDateString());
console.log("We are in ISO String the "+now.toISOString());

Management

Init

now = new Date();
date = new Date(2018,3,30);

Date.now

Date.now() returns the number of milliseconds in epoch scale and not a date object. It's equivalent to new Date().getTime().

Proof

console.log(Date.now() == new Date().getTime());

ToString

date = new Date();
console.log("Now in a Iso String format: "+date.toISOString());
  • Custom: There is already a lot of toString function but none of them give the ability to pass a string format. For example to go to YYYYMMDD
function pad(number) {
  if (number < 10) {
	return '0' + number;
  }
  return number;
}
date = new Date(2018,3,30);
dateString = date.getFullYear()+''+(pad(date.getMonth()+1))+''+date.getDate();
console.log(dateString);

Add / Subtstract

var today = new Date();
console.log("Today: "+today);
var tomorrow = new Date(today.getTime()+1000*60*60*24);
console.log("Tomorrow: "+tomorrow);

Compare

You can't compare date directly, you need to transform it to the time (a number that is the number of ms since epoch) and compare it.

Example:

var today = new Date();
var expirationDate = new Date(today.getTime() - 30);
if (expirationDate.getTime() < today.getTime()) {
  console.log("The date has expired");
}

TimeZone

Library

Documentation / Reference


Powered by ComboStrap