JavaScript – Dates

New Date()

Get’s current date, or pass a string or seconds passed since UNIX time 1/1/70 01:00

Date components have methods

const future = new Date(2037, 10, 19, 15, 23)
future.getFullYear();
future.getMonth();
future.getDate();
future.getDay();
future.getHours();
future.getMinutes()
future.getSeconds()
future.getISOString()
future.getTime(); // get timestamp

future.setFullYear(2040) // Modifies object

Operations with Dates

Convert date to a Number (+ or Number()) you can then perform maths on dates.

const calcDaysPassed = (date1, date2) => Math.abs(date2 - date1) / (1000 * 60 * 60 * 24);

Internationalizing Dates (Intl)

const now = new Date();
const options = {
 hour: 'numeric',
 minute: 'numeric',
 day: 'numeric',
 month: 'long',
 year: 'numeric',
 weekday: 'long'
}

new Intl.DateTimeFormat('en-US', options).format(now); // use ISO language code

const locale = navigator.language // Get ISO code from user's browser

Internationalizing Numbers (Intl)

new Intl.NumberFormat('en-US').format(num);

const options = {
  style: 'currency', // unit percent or currancy
  unit: 'celsius',
  currency: 'EUR'  // Not defined by locale so needs to be implied
  useGrouping: false // removes seperators
}

Leave a Reply

Your email address will not be published. Required fields are marked *