Where can I find documentation on formatting a date in JavaScript?

Asked
Active3 hr before
Viewed126 times

9 Answers

javascript
90%

I love 10 ways to format time and date using JavaScript and Working with Dates.,Basically, you have three methods and you have to combine the strings for yourself:,It is a (lightweight)* JavaScript date library for parsing, manipulating, and formatting dates.,The library sugar.js has some great functionality for working with dates in JavaScript. And it is very well documented.

Basically, you have three methods and you have to combine the strings for yourself:

getDate() // Returns the date
getMonth() // Returns the month
getFullYear() // Returns the year
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
console.log(curr_date + "-" + curr_month + "-" + curr_year);
load more v
88%

JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.,The following examples show how to determine the elapsed time between two JavaScript dates in milliseconds.,Report a problem with this content on GitHub,Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. Use negative numbers for times prior.

let today = new Date()
let birthday = new Date('December 17, 1995 03:24:00')
let birthday = new Date('1995-12-17T03:24:00')
let birthday = new Date(1995, 11, 17) // the month is 0-indexed
let birthday = new Date(1995, 11, 17, 3, 24, 0)
let birthday = new Date(628021800000) // passing epoch timestamp
load more v
72%

For a tutorial about date and times, read our JavaScript Date Tutorial.,The Date object is used to work with dates and times.,There are four ways of instantiating a date:,Date objects are created with new Date().

The Date object is used to work with dates and times.

Date objects are created with new Date().

new Date()
65%

The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as shown below −,The following method is used to Manipulate Dates in JavaScript −,How can I instantiate a dictionary in JavaScript where all keys map to the same value?,How can I get time and date since epoch in JavaScript?

The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as shown below −

new Date()
new Date(milliseconds)
new Date(datestring)
new Date(year, month, date[, hour, minute, second, millisecond])
75%

The call to Date.parse(str) parses the string in the given format and returns the timestamp (number of milliseconds from 1 Jan 1970 UTC+0). If the format is invalid, returns NaN.,Returns the timestamp for the date – a number of milliseconds passed from the January 1st of 1970 UTC+0.,An integer number representing the number of milliseconds that has passed since the beginning of 1970 is called a timestamp.,Create a Date object with the time equal to number of milliseconds (1/1000 of a second) passed after the Jan 1st of 1970 UTC+0.

let now = new Date();
alert(now); // shows current date/time
load more v
40%

format string can be composed of the following elements:,Formats date to a string based on the requested format.,format string can also be one of the following predefined localizable formats:,Formatted string or the input if input is not recognized as date/millis.

In HTML Template Binding

{
   {
      date_expression | date: format: timezone
   }
}

In JavaScript

$filter('date')(date, format, timezone)
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
    <span>{{1288323623006 | date:'medium'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
   <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
   <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
   <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
it('should format date', function() {
   expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
   toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
   expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
   toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/);
   expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
   toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
   expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
   toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
});
load more v
22%

I noticed that JavaScript's new Date() function is very smart in accepting dates in several formats. ,Where can we find documentation on formatting a date in JavaScript? ,When a single argument is passed to new Date(), it casts this function prototype: ,When two or more arguments are passed to new Date(), it casts this function prototype:

Xmas95 = new Date("25 Dec, 1995 23:15:00")
Xmas95 = new Date("2009 06 12,12:52:39")
Xmas95 = new Date("20 09 2006,12:52:39")
load more v
60%

Get the formatted date according to the string of tokens passed in.,To escape characters, wrap them in square brackets (e.g. [MM]).,Because preferred formatting differs based on locale, there are a few localized format tokens that can be used based on its locale.,More available formats Q Do k kk X x ... in plugin AdvancedFormat

To escape characters, wrap them in square brackets (e.g. [MM]).

dayjs().format()
// current date in ISO8601, without fraction seconds e.g. '2020-04-02T08:02:17-05:00'

dayjs('2019-01-25').format('[YYYYescape] YYYY-MM-DDTHH:mm:ssZ[Z]')
// 'YYYYescape 2019-01-25T00:00:00-02:00Z'

dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019'
load more v
48%

Most programming languages give you a formatting tool to create any Date format you want. For example, in PHP, you can write date("d M Y") to a date like 23 Jan 2019.,If you ever need to create a custom-formatted time, you can use the following methods:,Then, you combine all the variables you created to get the formatted string.,If you want to create dates, use arguments or timestamps.

In the date-string method, you create a date by passing a date-string into new Date.

new Date('1988-03-21')

In JavaScript, if you want to use a date string, you need to use a format that’s accepted worldwide. One of these formats is the ISO 8601 Extended format.

// ISO 8601 Extended format
`YYYY-MM-DDTHH:mm:ss.sssZ`

Hours, minutes, seconds and milliseconds are optional if you’re creating a date. So, if you want to create a date for , you can write this:

new Date('2019-06-11')

If you want to create a date in Local Time with the date-string method, you need to include the time. When you include time, you need to write the HH and mm at a minimum (or Google Chrome returns an invalid date).

new Date('2019-06-11T00:00')
  1. Year: 4-digit year.
  2. Month: Month of the year (0-11). Month is zero-indexed. Defaults to 0 if omitted.
  3. Day: Day of the month (1-31). Defaults to 1 if omitted.
  4. Hour: Hour of the day (0-23). Defaults to 0 if omitted.
  5. Minutes: Minutes (0-59). Defaults to 0 if omitted.
  6. Seconds: Seconds (0-59). Defaults to 0 if omitted.
  7. Milliseconds: Milliseconds (0-999). Defaults to 0 if omitted.
// 11th June 2019, 5:23:59am, Local Time
new Date(2019, 5, 11, 5, 23, 59)

Try reading numbers from left to right. As you go left to right, you insert values in decreasing magnitude: year, month, day, hours, minutes, seconds, and milliseconds.

new Date(2017, 3, 22, 5, 23, 50)

// This date can be easily read if you follow the left-right formula.
// Year: 2017,
// Month: April (because month is zero-indexed)
// Date: 22
// Hours: 05
// Minutes: 23
// Seconds: 50

Here are some more examples for you to familiarize yourself:

// 21st March 1988, 12am, Local Time.
new Date(1988, 2, 21)

// 25th December 2019, 8am, Local Time.
new Date(2019, 11, 25, 8)

// 6th November 2023, 2:20am, Local Time
new Date(2023, 10, 6, 2, 20)

// 11th June 2019, 5:23:59am, Local Time
new Date(2019, 5, 11, 5, 23, 59)

That’s one of the perks of using arguments—you won’t get confused between Local Time and UTC. If you ever need UTC, you create a date in UTC this way:

// 11th June 2019, 12am, UTC.
new Date(Date.UTC(2019, 5, 11))

In JavaScript, a timestamp is the amount of milliseconds elapsed since 1 January 1970 (1 January 1970 is also known as Unix epoch time). From my experience, you rarely use timestamps to create dates. You only use timestamps to compare between different dates (more on this later).

// 11th June 2019, 8am (in my Local Time, Singapore)
new Date(1560211200000)

If you create a date without any arguments, you get a date set to the current time (in Local Time).

new Date()

The native Date object comes with seven formatting methods. Each of these seven methods give you a specific value (and they’re quite useless).

const date = new Date(2019, 0, 23, 17, 23, 42)

It’s simple to create 23 and 2019 for Thu, 23 January 2019. We can use getFullYear and getDate to get them.

const d = new Date(2019, 0, 23)
const year = d.getFullYear() // 2019
const date = d.getDate() // 23

To get January, you need to create an object that maps the value of all twelve months to their respective names.

const months = {
   0: 'January',
   1: 'February',
   2: 'March',
   3: 'April',
   4: 'May',
   5: 'June',
   6: 'July',
   7: 'August',
   8: 'September',
   9: 'October',
   10: 'November',
   11: 'December'
}

Since Month is zero-indexed, we can use an array instead of an object. It produces the same results.

const months = [
   'January',
   'February',
   'March',
   'April',
   'May',
   'June',
   'July',
   'August',
   'September',
   'October',
   'November',
   'December'
]
  1. Use getMonth to get the zero-indexed month from the date.
  2. Get the month name from months
const monthIndex = d.getMonth()
const monthName = months[monthIndex]
console.log(monthName) // January

The condensed version:

const monthName = months[d.getMonth()]
console.log(monthName) // January

You do the same thing to get Thu. This time, you need an array that contains seven days of the week.

const days = [
   'Sun',
   'Mon',
   'Tue',
   'Wed',
   'Thu',
   'Fri',
   'Sat'
]
  1. Get dayIndex with getDay
  2. Use dayIndex to get dayName
const dayIndex = d.getDay()
const dayName = days[dayIndex] // Thu

Short version:

const dayName = days[d.getDay()] // Thu

Then, you combine all the variables you created to get the formatted string.

const formatted = `${dayName}, ${date} ${monthName} ${year}`
console.log(formatted) // Thu, 23 January 2019

If you want to know whether a date comes before or after another date, you can compare them directly with >, <, >= and <=.

const earlier = new Date(2019, 0, 26)
const later = new Date(2019, 0, 27)

console.log(earlier < later) // true

It’s more difficult if you want to check if two dates fall exactly at the same time. You can’t compared them with == or ===.

const a = new Date(2019, 0, 26)
const b = new Date(2019, 0, 26)

console.log(a == b) // false
console.log(a === b) // false

To check whether two dates fall exactly at the same time, you can check their timestamps with getTime.

const isSameTime = (a, b) => {
   return a.getTime() === b.getTime()
}

const a = new Date(2019, 0, 26)
const b = new Date(2019, 0, 26)
console.log(isSameTime(a, b)) // true

If you want to check whether two dates fall on the same day, you can check their getFullYear, getMonth and getDate values.

const isSameDay = (a, b) => {
   return a.getFullYear() === b.getFullYear() &&
      a.getMonth() === b.getMonth() &&
      a.getDate() === b.getDate()
}

const a = new Date(2019, 0, 26, 10) // 26 Jan 2019, 10am
const b = new Date(2019, 0, 26, 12) // 26 Jan 2019, 12pm
console.log(isSameDay(a, b)) // true

For example, if you want to set a date to the 15th of the month, you can use setDate(15).

const d = new Date(2019, 0, 10)
d.setDate(15)

console.log(d) // 15 January 2019

If you want to set the month to June, you can use setMonth. (Remember, month in JavaScript is zero-indexed!)

const d = new Date(2019, 0, 10)
d.setMonth(5)

console.log(d) // 10 June 2019

Note: The setter methods above mutate the original date object. In practice, we should not mutate objects (more on why here). We should perform these operations on a new date object instead.

const d = new Date(2019, 0, 10)
const newDate = new Date(d)
newDate.setMonth(5)

console.log(d) // 10 January 2019
console.log(newDate) // 10 June 2019
The first approach (the set approach)
// Assumes today is 28 March 2019
const today = new Date(2019, 2, 28)

First, we create a new Date object (so we don’t mutate the original date)

const finalDate = new Date(today)

Next, we need to know the value we want to change. Since we’re changing days, we can get the day with getDate.

const currentDate = today.getDate()

We want a date that’s three days from today. We’ll use add the delta (3) to the current date.

finalDate.setDate(currentDate + 3)

Full code for the set approach:

const today = new Date(2019, 2, 28)
const finalDate = new Date(today)
finalDate.setDate(today.getDate() + 3)

console.log(finalDate) // 31 March 2019

Here, we use getFullYear, getMonth, getDate and other getter methods until we hit the type of value we want to change. Then, we use create the final date with new Date.

const today = new Date(2019, 2, 28)

// Getting required values
const year = today.getFullYear()
const month = today.getMonth()
const day = today.getDate()

// Creating a new Date (with the delta)
const finalDate = new Date(year, month, day + 3)

console.log(finalDate) // 31 March 2019

Here’s an example. Let’s say we set date to . (There’s no 33rd March on the calendar). In this case, JavaScript adjusts 33rd March to 2nd April automatically.

// 33rd March => 2nd April
new Date(2019, 2, 33)

This means you don’t need to worry about calculating minutes, hours, days, months, etc. when creating a delta. JavaScript handles it for you automatically.

// 33rd March => 2nd April
new Date(2019, 2, 30 + 3)
load more v

Other "javascript-undefined" queries related to "Where can I find documentation on formatting a date in JavaScript?"