Formatting Dates in JavaScript

The AuraLocalizationService JavaScript API provides methods for formatting and localizing dates.

For example, the formatDate() method formats a date based on the formatString parameter set as the second argument.

1formatDate (String | Number | Date date, String formatString)

The date parameter can be a String, Number, or most typically a JavaScript Date. If you provide a String value, use ISO 8601 format to avoid parsing warnings.

The formatString parameter contains tokens to format a date and time. For example, "YYYY-MM-DD" formats 15th January, 2017 as "2017-01-15". The default format string comes from the $Locale value provider.

This table shows the list of tokens supported in formatString.

DescriptionTokenOutput
Day of monthd1 … 31
Day of monthdd01 … 31
Day of month. Deprecated. Use dd, which is identical.DD01 … 31
Day of week (number)E0 … 6
Day of week (short name)EEESun … Sat
Day of week (long name)EEEESunday … Saturday
MonthM1 … 12
MonthMM01 … 12
Month (short name)MMMJan … Dec
Month (full name)MMMMJanuary … December
Year (two digits)yy17
Year (four digits)yyyy2017
Year. Deprecated. Use yyyy, which is identical.y2017
Year. Deprecated. Use yyyy, which is identical.Y2017
Year. Deprecated. Use yy, which is identical.YY17
Year. Deprecated. Use yyyy, which is identical.YYYY2017
Hour of day (1-12)h1 … 12
Hour of day (0-23)H0 … 23
Hour of day (00-23)HH00 … 23
Hour of day (1-24)k1 … 24
Hour of day (01-24)kk01 … 24
Minutem0 … 59
Minutemm00 … 59
Seconds0 … 59
Secondss00 … 59
Fraction of secondSSS000 … 999
AM or PMaAM or PM
AM or PM. Deprecated. Use a, which is identical.AAM or PM
Zone offset from UTCZ-12:00 … +14:00
Quarter of yearQ1 … 4
Week of yearw1 … 53
Week of yearww01 … 53

There are similar methods that differ in their default output values.

  • formatDateTime()—The default formatString outputs datetime instead of date.
  • formatDateTimeUTC()—Formats a datetime in UTC standard time.
  • formatDateUTC()—Formats a date in UTC standard time.

For more information on all the methods in AuraLocalizationService, see JavaScript API.

This example converts a selected date on a date field using the given format, yyyy-MM-dd. The converted date is displayed below the date field.

1<aura:component implements="flexipage:availableForRecordHome">
2    <aura:attribute name="formatDate" type="String"/>
3    <lightning:input
4        type="date"
5        value="{!v.formatDate}"
6        onchange="{!c.convertDate}">
7    </lightning:input>
8    {!v.formatDate}
9</aura:component>
1({
2    convertDate: function (cmp, event) {
3        var date = event.getParam("value");
4        var formatted = $A.localizationService.formatDate(date, "yyyy-MM-dd");
5        cmp.set("v.formatDate", formatted);
6    },
7})

See Also