Time and Date

Page section: posts
More on date

For time and date you use Javascript’s built in date object. Typically you will store a date in a variable.

const now = new Date();

This will grab the current time and date when the script is run.

There are 9 ways to store dates in the Date() object.

code example notes
new Date() new Date() The current time at runtime.
new Date(date string) new Date(..)
new Date(year,month) new Date(1980, 11) You need a minimum of two values to avoid the time elapsed in milliseconds
new Date(year,month,day) new Date(1980, 11, 31)
new Date(year,month,day,hours) new Date(1980, 11, 31, 15)
new Date(year,month,day,hours,minutes) new Date(1980, 11, 31, 15, 25)
new Date(year,month,day,hours,minutes,seconds) new Date(1980, 11, 31, 15, 25, 45)
new Date(year,month,day,hours,minutes,seconds,ms) new Date(1980, 11, 31, 15, 25, 45, 258)
new Date(milliseconds) new Date(0) With a single value this is interpreted as milliseconds since 1/1/1970. Thus with a value of 0 you get that date.

Using the ISO date string is also simple. Don’t forget the quotes though which are not required for the above, comma separated values.

const myDate = new Date('2011-03-17');

// with hours, mins and seconds
const myDate = new Date('2011-03-17T13:10:52');

otherwise using a comma separated list:

const myDate = new Date(2011, 03, 17, 19, 22, 34);

The last 3 figures are hours, minutes and seconds. You don’t need to use all 6 figures but you do need at least the year and the month. You could just use the year and month or anything after that: year, month, day

new Date()

get and set methods

Once we have a new Date() object, stored in a variable called now there are various methods to extract or alter part of the date or time. To extract or get part of the date object the following methods are used:

With a date object stored in a variable named now

code current
value
what it does
now.getTime() the number of milliseconds that have elapsed in 1/1/1970 (aka epoch time. The number is negative for dates before that)
now.getFullYear() the year in 4 digits
now.getMonth() the month in single or double digits starting at 0
now.getDate() the day of the month from 1 to 31
now.getDay() the day of the week counting from 0 to 6. Sunday is the first day represented by 0.
now.getMinutes() minutes past the hour
now.getHours() hours from 0 to 23 count starting at midnight
now.getSeconds() seconds past the current minute
now.getMilliseconds() milliseconds past the current second
now.getYear() DEPRECATED

The set methods are very similar same starting with set instead of get.

You can set UTC times by adding UTC after set. For example: setUTCHours()

Examples

This is UNIX time which is the amount of milliseconds that have passed since Jan 1st 1970. For dates prior to this simply use negative values.

Fixed dates

You can add fixed date to a new Date() object.

const einsteinBirthday = new Date('1879-03-14');

To get his age is a simple calcuation.

now.getFullYear() - einsteinBirthday.getFullYear();

Autocorrection

Dates that are out-of-range will auto correct. If the number of say the date is higher the possible days of the month the extra days are added on to the following month. So if a day is given the number 45 when there are only 30 days in the month the date will be the 15th day of the following month.

Getting the date in a specific format

Getting a simple day and month is bit more convoluted.

  1. Create a date object for today: const today = new Date();
  2. Create two more variables, one storing the day and on the month:
const day = today.getDate();
const month = today.getMonth();
  1. Finally combine these in another variable:
const dayMonth = `${day} / ${month}`;

p5 is ready

Getting the name of a month or day of the week

There are couple of ways to get name of the month, rather than it’s 0 based number.

Using an array

The first way we must first create an array of months:

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

Notice that to pull one month of this array out will use the same numbers as those that can be accessed by the Date() object, ie from 0 to 11.

const thisMonth = now.getMonth();
p6El.innerHTML = 'the month is: ' + months[thisMonth];

You can get the day of the week the same way. The first day is Sunday which is represented by 0 when accessed using the getDay() method.

p6 is ready

Using toLocaleString()

Another way is to use the toLocaleString() method to get the day or month.

On it’s own toLocaleString() creates a string of time and date from date object like this:

p8 is ready

However there are various ways to modify toLocaleString() including getting the name of the weekday or the name of the month in both long and short formats.

const stringMonth = now.toLocaleString('default', { month: 'long' });
const stringDay = now.toLocaleString('default', { weekday: 'long' });

The format of these can be either long or short, February or Feb, Saturday or Sat.

p7 is ready

There is also toLocaleDateString and toLocaleTimeString

p9 ready

Date.now()

Using Date.now() creates a timestamp of the time now without creating a new Date() object. It gives the time in milliseconds since epoch time. The output is the same as using the getTime() method.

It is used mostly for convenience or when performance matters, like in games in JavaScript or other specialized applications.

javascript.info


View contents of: /static/js/time-and-date.js
const p1El = document.querySelector('#p1');
const p2El = document.querySelector('#p2');
const p3El = document.querySelector('#p3');
const p4El = document.querySelector('#p4');
const p5El = document.querySelector('#p5');
const p6El = document.querySelector('#p6');
const p7El = document.querySelector('#p7');
const p9El = document.querySelector('#p9');

const now = new Date();
const epochTime = new Date(0);

const einsteinBirthday = new Date('1879-3-14');
// let einsteinAge = now - einsteinBirthday;
const einsteinYear = einsteinBirthday.getFullYear();
let thisYear = now.getFullYear();
let einsteinAge = thisYear - einsteinYear;

p1El.innerHTML = 'What the <code>new Date()</code> returns:<br>' + now;
p2El.innerHTML = 'Using <code>now.getTime</code>: ' + now.getTime();
p3El.innerHTML =
  'Using <code>new Date(0)</code> to get epoch time:<br>' + epochTime;
p4El.innerHTML = `Einstein was born in ${einsteinBirthday.getFullYear()}.`;
// If he was alive today he would be: ${einsteinAge.getYear()}`;

p5El.innerHTML = `p5 is here`;

p4El.innerHTML = `Einstein was born in ${einsteinBirthday.getFullYear()}. If he was alive today he would be: ${einsteinAge}`;

let month = now.getMonth() + 1;
let day = now.getDate();

const dayMonth = day + '/' + month;

p5El.innerHTML = 'Today is: ' + dayMonth;

const months = [
  'Jan',
  'Feb',
  'Mar',
  'Apr',
  'May',
  'Jun',
  'Jul',
  'Aug',
  'Sep',
  'Oct',
  'Nov',
  'Dec',
];

const today = now.getDay();
const daysOfTheWeek = [
  'Sunday',
  'Monday',
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday',
  'Saturday',
];

const thisMonth = now.getMonth();

p6El.innerHTML = `the month is: ${months[thisMonth]} and today is ${daysOfTheWeek[today]}`;

const stringMonth = now.toLocaleString('default', { month: 'long' });

const stringDay = now.toLocaleString('default', { weekday: 'long' });

p7El.innerHTML = `Today is ${stringDay}. The month is ${stringMonth}.`;

const toLocale = now.toLocaleString();
const toDate = now.toDateString();
const toLocaleDate = now.toLocaleDateString();
const toTime = now.toTimeString();
const toLocaleTime = now.toLocaleTimeString();
const toISO = now.toISOString();

// p8El.innerHTML = 'tls';

p9El.innerHTML = `
Using <code>toLocaleString()</code>: ${toLocale} <br>
Using <code>toDateString()</code>: ${toDate} <br>
Using <code>toLocaleDateString()</code>: ${toLocaleDate} <br>
Using <code>toTimeString()</code>: ${toTime}<br>
Using <code>toLocaleTimeString()</code>: ${toLocaleTime}<br>
Using <code>toISOString()</code>: ${toISO}
`;

// alert(stringDay);

Table of Contents