Skip to content

Format Date in JavaScript

Create a Date

In Javascript, you can use the new Date() constructor to create a new Date object.

javascript
let now = new Date() // current date and time
let date1 = new Date(1700320703000); // passing milliseconds epoch timestamp
let date2 = new Date(2023, 11, 18, 3, 24, 0); //year, monthIndex, day, hours, minutes, seconds (the month is 0-indexed)
let date3 = new Date("2023-11-18T03:24:00")
var date4 = new Date("2023-11-18T03:24:00.000+08:00"); //YYYY-MM-DDTHH:mm:ss.sssZ

Get Current Unixt timestamp

javascript
let timestamp1 = new Date().getTime() //UNIX epoch timestamp in milliseconds
let timestamp2 = Math.round(new Date().getTime() / 1000) //UNIX epoch timestamp in seconds

toString()

javascript
let now = new Date()
console.log(now.toString()) //Fri Nov 17 2023 16:02:55 GMT+0800 (China Standard Time)

toDateString()

javascript
let now = new Date()
console.log(now.toDateString()) //Fri Nov 17 2023

toLocaleString()

toLocaleString(locales, options)

javascript
let now = new Date()
console.log(now.toLocaleString()) // 11/17/2023, 4:02:55 PM
console.log(now.toLocaleString('en-US')) // 11/17/2023, 4:02:55 PM
console.log(now.toLocaleString('en-US',{ timeZone: 'US/Pacific' })) // 11/17/2023, 12:02:55 AM
console.log(now.toLocaleString('zh-CN')) // 2023/11/17 16:02:55
console.log(now.toLocaleString('zh-CN',{ timeZone: 'UTC' })) // 2023/11/17 08:02:55

ToLocaleDateString()

javascript
let now = new Date()
const options = {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
};
console.log(now.toLocaleDateString()) // 11/17/2023
console.log(now.toLocaleDateString('en-US')) // 11/17/2023
console.log(now.toLocaleDateString('en-US',options)) // Friday, November 17, 2023
console.log(now.toLocaleDateString('zh-CN')) // 2023/11/17
console.log(now.toLocaleDateString('zh-CN',options)) // 2023年11月17日星期五

ToLocaleTimeString()

javascript
let now = new Date()
console.log(now.toLocaleTimeString()) // 4:02:55 PM
console.log(now.toLocaleTimeString('en-US')) // 4:02:55 PM
console.log(now.toLocaleTimeString('zh-CN')) // 16:02:55

toUTCString()

javascript
let now = new Date()
console.log(now.toUTCString()) //Fri, 17 Nov 2023 08:02:55 GMT

toISOString()

Format a date as an ISO 8601 format. The timezone is always UTC, as denoted by the suffix Z.

javascript
let now = new Date()
console.log(now.toISOString()) //2023-11-17T08:02:55.274Z

RFC3339 Format

Format a date as an RFC 3339 format with timezone.

javascript
function rfc3339(d) {
    
    function pad(n) {
        return n < 10 ? "0" + n : n;
    }

    function timezoneOffset(offset) {
        var sign;
        if (offset === 0) {
            return "Z";
        }
        sign = (offset > 0) ? "-" : "+";
        offset = Math.abs(offset);
        return sign + pad(Math.floor(offset / 60)) + ":" + pad(offset % 60);
    }

    return d.getFullYear() + "-" +
        pad(d.getMonth() + 1) + "-" +
        pad(d.getDate()) + "T" +
        pad(d.getHours()) + ":" +
        pad(d.getMinutes()) + ":" +
        pad(d.getSeconds()) + 
        timezoneOffset(d.getTimezoneOffset());
}

const now = new Date();
console.log(rfc3339(now)) // 2023-11-21T15:55:12+08:00

Get Current time zone and supported time zone list

javascript
const now = new Date();
console.log(now.getTimezoneOffset()) // -480
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone) //Asia/Shanghai
console.log(Intl.supportedValuesOf('timeZone')); //Get timezones list

Format Date to another timezone

JavaScript Date object does not store any timezone information (it contains unix timestamp inside, and when you call .getMinutes (), getHours (), toString () it uses system timezone). So if you want to format a Date to another timezone, you need to use moment-timezone.

javascript
const moment = require('moment-timezone');
const now = new Date()
console.log(now.toString()) //default timezone: Wed Nov 22 2023 12:13:10 GMT+0800 (China Standard Time)
console.log(moment(now).toString()) //default timezone: Wed Nov 22 2023 12:13:10 GMT+0800
console.log(moment(now).tz("America/New_York").toString()) //New York Timezone: Tue Nov 21 2023 23:13:10 GMT-0500
console.log(moment(now).tz("America/New_York").toDate().toString()) //Convert to Date Object, use default timezone: Wed Nov 22 2023 12:13:10 GMT+0800 (China Standard Time)

Get User Locale

javascript
const locale = (navigator && navigator.language) || "en"; 
console.log(locale); // en-US

Parameters

locales

localeMeaning
ar-SAArabic (Saudi Arabia)
ar-SAArabic (Saudi Arabia)
bn-BDBangla (Bangladesh)
bn-INBangla (India)
cs-CZCzech (Czech Republic)
da-DKDanish (Denmark)
de-ATAustrian German
de-CH"Swiss" German
de-DEStandard German (as spoken in Germany)
el-GRModern Greek
en-AUAustralian English
en-CACanadian English
en-GBBritish English
en-IEIrish English
en-INIndian English
en-NZNew Zealand English
en-USUS English
en-ZAEnglish (South Africa)
es-ARArgentine Spanish
es-CLChilean Spanish
es-COColombian Spanish
es-ESCastilian Spanish (as spoken in Central-Northern Spain)
es-MXMexican Spanish
es-USAmerican Spanish
fa-IRIranian (Iran)
fi-FIFinnish (Finland)
fr-BEBelgian French
fr-CACanadian French
fr-CH"Swiss" French
fr-FRStandard French (especially in France)
he-ILHebrew (Israel)
hi-INHindi (India)
hu-HUHungarian (Hungary)
id-IDIndonesian (Indonesia)
it-CH"Swiss" Italian
it-ITStandard Italian (as spoken in Italy)
ja-JPJapanese (Japan)
ko-KRKorean (Republic of Korea)
nl-BEBelgian Dutch
nl-NLStandard Dutch (as spoken in The Netherlands)
no-NONorwegian (Norway)
pl-PLPolish (Poland)
pt-BRBrazilian Portuguese
pt-PTEuropean Portuguese (as written and spoken in Portugal)
ro-RORomanian (Romania)
ru-RURussian (Russian Federation)
sk-SKSlovak (Slovakia)
sv-SESwedish (Sweden)
ta-INIndian Tamil
ta-LKSri Lankan Tamil
th-THThai (Thailand)
tr-TRTurkish (Turkey)
zh-CNMainland China, simplified characters
zh-HKHong Kong, traditional characters
zh-TWTaiwan, traditional characters

options

keyoptions
dateStyle"full","long","medium","short"
timeStyle"full","long","medium","short"
localeMatcher"best-fit" (default), "lookup"
timeZone
hour12false,true
hourCycle"h11","h12","h23","h24"
formatMatcher"basic","best-fit" (default)
weekday"long","short","narrow"
year"2-digit","numeric"
month"2-digit","long","narrow","numeric","short"
day"2-digit","numeric",hour "2-digit","numeric"
minute"2-digit","numeric"
second"2-digit","numeric"
timeZoneName"long","short"