How to manipulate and show a Date Time in Javascript?

About

In javascript, date time information is represented in a a date object that:

  • encapsulates the epoch time in milliseconds
  • is timezone-agnostic

Example

const now = new Date();
console.log("We are the "
   +now.getDate()
   // getMonth'' function is 0 based. Therefore January is at 0 and not 1
   +"-"+(now.getMonth()+1)
   // the ''getYear'' function is deprecated for ''getFullYear'' - due to a ''year 2000 problem'', this function does not return a valid year number.
   +"-"+now.getFullYear());
console.log("We are in toString (local time) the "+now.toString());
console.log("We are in toLocaleString (local time) the "+now.toLocaleString());
console.log("We are in Date String (local time) the "+now.toDateString());
console.log("We are in ISO String (UTC time) the "+now.toISOString());

Management

Init

Current time

now = new Date();

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());
console.log(Date.now() == new Date().getTime());
console.log((new Date(Date.now())).toString());

From Calendar Numbers

  • Date level
let date = new Date(2018,3,30);
const time = { "year": date.getFullYear(), "month": date.getMonth(), "day": date.getDate(), "hours": date.getHours(), "minutes": date.getMinutes(), "seconds": date.getSeconds() };
console.log(time);
  • At the second level
new Date(1973, 07, 20, 8, 30, 0)

From epoch

With an epoch timestamp

let epoch = Date.now(); 
console.log("The current epoch is "+epoch);
let date = new Date(epoch);
const time = { "year": date.getFullYear(), "month": date.getMonth(), "day": date.getDate(), "hours": date.getHours(), "minutes": date.getMinutes(), "seconds": date.getSeconds() };
console.log(time);

From String

let date = new Date('2022-02-18T09:34:32.255Z');
const time = { "year": date.getFullYear(), "month": date.getMonth(), "day": date.getDate(), "hours": date.getHours(), "minutes": date.getMinutes(), "seconds": date.getSeconds() };
console.log(time);
let epoch = Date.parse('2022-02-18T09:34:32.255Z');
console.log(epoch);
let date = new Date(epoch );
const time = { "year": date.getFullYear(), "month": date.getMonth(), "day": date.getDate(), "hours": date.getHours(), "minutes": date.getMinutes(), "seconds": date.getSeconds() };
console.log(time);

ToString

To Iso8601 String

date = new Date();
console.log("Now in a Iso String format: "+date.toISOString());

To Date String

let date= new Date();
console.log(date.toDateString());

To Only Time Part (Hour, Min, Sec)

let date= new Date();
console.log(date.toLocaleTimeString()); // without zone
console.log(date.toTimeString()); // with zone

To Custom String with string format such as SQL Timestamp String

Custom: There is already a lot of toString functions but none of them give the ability to pass a string format.

The whole Javascript formatting is based on the Intl.DateTimeFormat function that permits to:

  • Format directly with its format function
  • Extract the formatted parts with the formatToParts function

Unfortunately, this function does not support a date format string pattern.

For example, the SQL timestamp string

  • the YYYY-MM-DD date level format with parts extraction
const date = new Date(2018,3,1);
const format = Intl.DateTimeFormat(window.navigator.language, {
  day: "2-digit", 
  year: "numeric", 
  month: "2-digit"
  });
const formatParts = Object.fromEntries(
   format.formatToParts(date).map(e=> [e.type,e.value])
   );
dateString = `${formatParts.year}-${formatParts.month}-${formatParts.day}`;
console.log(dateString);
date = new Date();
dateString = `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')} ${date.getHours().toString().padStart(2,'0')}:${date.getMinutes().toString().padStart(2,'0')}:${date.getSeconds().toString().padStart(2,'0')}`;
console.log(dateString);

to Locale Relative Time string

If you want to output time in a Locale relative to today, you can use the RelativeTimeFormat

Example with French

const relativeOptions = { numeric: 'auto' }; // Intl.RelativeTimeFormatOptions
const relativeFormatter = new Intl.RelativeTimeFormat("fr", relativeOptions);
console.log(relativeFormatter.format(120,"minute"))
console.log(relativeFormatter.format(-120,"minute"))
console.log("Parts")
console.log(relativeFormatter.formatToParts(120,"minute")[0])
console.log(relativeFormatter.formatToParts(120,"minute")[1])
console.log(relativeFormatter.formatToParts(120,"minute")[2])

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

See Javascript - TimeZone

High Resolution Time

The following script may record a positive number, negative number, or zero for computed duration: High Resolution API tries to correct this behavior 2)

var mark_start = Date.now();
doTask(); // Some task
var duration = Date.now() - mark_start;

Library

3)





Discover More
Card Puncher Data Processing
Datacadamia - Data all the things

Computer science from a data perspective
Javascript - String

The in javascript. A string in JavaScript is encoded with the ucs-2 16-bit character set. An element of a JavaScript string is therefore a 16-bit code unit. code unitscode pointssurrogate pair Strings...
Javascript - Time

See
Javascript - Type

Type in Javascript Javascript is not static typed but it exist Javascript wrapper language that implements it. See Only values have types in JavaScript; variables are just simple containers for those...
Browser
Puppeteer - How to pass back and forth a date (or a complex type) to the headless browser via the evaluate function

A step by step guide that shows how to serialize and deserialize an object with a date ( ) when using the puppeteer evaluate...



Share this page:
Follow us:
Task Runner