Tutorial

Exploring the JavaScript Date Object

A concise, original guide to the JavaScript Date object: creating dates, timestamps, formatting, UTC vs local time, get/set methods, and practical examples.

Drake Nguyen

Founder · System Architect

3 min read
Exploring the JavaScript Date Object
Exploring the JavaScript Date Object

Overview: Using the JavaScript Date object

For many projects you don’t need a heavy library to handle time and dates. The native JavaScript Date object provides built-in tools for parsing, formatting, converting timestamps and working with local vs UTC time. This guide explains how to use the JavaScript Date object with practical examples and best practices for common tasks like getting a JavaScript timestamp, formatting a date in JavaScript without libraries, and converting local time to UTC.

Creating Date objects

You can create a Date() JavaScript instance in several ways depending on whether you want the current time, a timestamp, an ISO string, or components for year/month/day.

Current date and time

const now = new Date();
console.log(now); // Current date/time in your local timezone

Create from milliseconds (timestamp)

Pass an integer representing milliseconds since the Unix epoch (Jan 1, 1970 UTC) to create a date from a timestamp.

// create date from timestamp JavaScript
const fromTs = new Date(1_600_000_000_000);
console.log(fromTs);

Parse ISO date strings

The Date constructor also accepts ISO-style strings. Adding a trailing Z forces UTC parsing.

// parse ISO date string JavaScript Date
const iso = new Date('2020-09-13T12:34:56Z');
console.log(iso);

Using date components

You can supply year, month, day and optionally hours, minutes, seconds and milliseconds. Note: months are zero-based.

// JavaScript Date object examples
const comps = new Date(2021, 0, 31, 14, 20); // January is month 0
console.log(comps);
Tip: "JavaScript Date getMonth zero based" means January === 0 and December === 11. Adjust accordingly when displaying months to users.

Timestamps and Date.now

To get milliseconds since the Unix epoch you can use either an instance method or a static method.

  • new Date().getTime() — returns the timestamp for that Date instance.
  • Date.now() — returns the current timestamp directly. This is concise and fast.
// Date.now vs new Date().getTime
const t1 = new Date().getTime();
const t2 = Date.now();
console.log(t1 === t2); // typically true

Human-readable output and formatting

The Date prototype exposes several methods for readable output and locale-aware formatting, such as toDateString, toTimeString, toUTCString and toLocaleString.

const d = new Date();
console.log(d.toDateString());      // e.g. "Tue Sep 13 2022"
console.log(d.toTimeString());      // time portion with timezone
console.log(d.toUTCString());       // JavaScript UTC date example
console.log(d.toLocaleString());    // JavaScript toLocaleString (locale aware)

If you need a custom JavaScript date format without pulling in a library, combine getters to build strings manually.

// format date in JavaScript without libraries
function formatYYYYMMDD(date){
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`;
}
console.log(formatYYYYMMDD(new Date()));

Getting date and time components

The Date object provides getters for both local time and UTC time. Use the UTC equivalents when you need timezone-independent values.

  • getFullYear(), getMonth(), getDate(), getDay()
  • getHours(), getMinutes(), getSeconds(), getMilliseconds()
  • getUTCFullYear(), getUTCMonth(), getUTCDate(), getUTCHours(), etc.
const now = new Date();
console.log(now.getHours(), now.getMinutes()); // local
console.log(now.getUTCHours(), now.getUTCMinutes()); // UTC

Setting components and mutating dates

You can change parts of a date using set methods. Some setters accept multiple arguments and will update dependent fields accordingly.

const d = new Date();
d.setFullYear(2049);
// setMonth accepts 0-11
d.setMonth(11); // December
console.log(d.toLocaleString());

Adding or subtracting time

To add minutes, hours, days or other units, use getters and setters or perform arithmetic on timestamps.

// add 15 minutes using get/set
const start = new Date();
start.setMinutes(start.getMinutes() + 15);
console.log(start.toLocaleTimeString());

// or using timestamps for larger calculations
const later = new Date(Date.now() + 1000 * 60 * 60 * 24); // +1 day
console.log(later);

Common pitfalls and best practices

  • Be mindful of zero-based months when reading or displaying month values.
  • Prefer Date.now() for current timestamps — it is clearer than new Date().getTime().
  • Use UTC getters/setters when comparing moments across time zones to avoid daylight savings issues.
  • For complex date math or advanced time zone support consider a well-maintained library, but for many tasks the native JS date API is enough.

Quick reference: useful methods

  • new Date(), Date.now(), new Date(ms)
  • getTime(), toUTCString(), toLocaleString()
  • getFullYear(), getMonth(), getDate(), getHours(), getMinutes()
  • setFullYear(), setMonth(), setDate(), setHours(), setMinutes()

Further reading

Try examples like "how to use the JavaScript Date object" and "Date.now vs new Date().getTime" as search terms to explore more use cases and JavaScript Date object examples.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.