Skip to content
Fix Code Error

How to format a JavaScript date

March 13, 2021 by Code Error
Posted By: Anonymous

In JavaScript, how can I format a date object to print as 10-Aug-2010?

Solution

For custom-delimited date formats, you have to pull out the date (or time)
components from a DateTimeFormat object (which is part of the
ECMAScript Internationalization API), and then manually create a string
with the delimiters you want.

To do this, you can use DateTimeFormat#formatToParts. You could
destructure the array, but that is not ideal, as the array output depends on the
locale:

// example 1
const o_date_en = new Intl.DateTimeFormat('en');
const a_date_en = o_date_en.formatToParts();
// example 2
const o_date_hi = new Intl.DateTimeFormat('hi');
const a_date_hi = o_date_hi.formatToParts();
// print
console.log(a_date_en, a_date_hi);

Better would be to reduce the array into an object:

const o_date = new Intl.DateTimeFormat;
const f_date = (m_ca, m_it) => Object({...m_ca, [m_it.type]: m_it.value});
const m_date = o_date.formatToParts().reduce(f_date, {});
console.log(m_date.day + '-' + m_date.month + '-' + m_date.year);

You can also pull out the parts of a DateTimeFormat one-by-one using
DateTimeFormat#format, but note that when using this method, as of March
2020, there is a bug in the ECMAScript implementation when it comes to
leading zeros on minutes and seconds (this bug is circumvented by the approach
above).

const d = new Date(2010, 7, 5);
const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
console.log(`${da}-${mo}-${ye}`);

When working with dates and times, it is usually worth using a library (eg.
moment.js, luxon) because of the many hidden complexities of the
field.

Note that the ECMAScript Internationalization API, used in the solutions above
is not supported in IE10 (0.03% global browser market share in Feb
2020).

Answered By: Anonymous

Related Articles

  • How to retrieve a value from a different column by…
  • How To Initialize Internationalization For A Polymer…
  • Best way to do multi-row insert in Oracle?
  • Set Locale programmatically
  • Python is not calling fucntions properly
  • How to change language of app when user selects language?
  • Vuetify issue with v-menu
  • Java SimpleDateFormat for time zone with a colon separator?
  • Aurelia validate one datetime is greater than the other
  • Vue i18n - adding locale to the URL using routerview
  • Java string to date conversion
  • Changing Locale within the app itself
  • python pandas extract year from datetime: df['year']…
  • Vue-router translating url
  • How do I resolve `The following packages have unmet…
  • Next.js 10 + sub-routing, how to access locale in…
  • vue-i18n $t with values attribute is not translating
  • How do I include certain conditions in SQL Count
  • Current time formatting with Javascript
  • Convert Java Date to UTC String
  • How do I set the default locale in the JVM?
  • Python Loop through url json data not storing the…
  • How do I get a list of all the duplicate items using…
  • Next.js router locale issue
  • How to internationalize a React Native Expo App?
  • How do I format a date with Dart?
  • How does PHP 'foreach' actually work?
  • Examples of GoF Design Patterns in Java's core libraries
  • Sorting a 2D string array in c
  • Python Pandas replicate rows in dataframe
  • What's the difference between Instant and LocalDateTime?
  • Logging best practices
  • java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
  • Conflict on Template of Twig and Vue.js
  • How to change the color of vaadin-select-text-field…
  • How to format Joda-Time DateTime to only mm/dd/yyyy?
  • For-each over an array in JavaScript
  • Can I add custom translations to Vuetify datepicker?
  • pip install - locale.Error: unsupported locale setting
  • How to internationalize a handlebars + backbone view?
  • SQL Server Group By Month
  • Detect whether Office is 32bit or 64bit via the registry
  • Smart way to truncate long strings
  • vue-i18n doesn't update locale after integrating vuex
  • How to get Locale from its String representation in Java?
  • How to set global delimiters in Vue.js 2.0?
  • Redirecting to the same page but switched language…
  • What is an optional value in Swift?
  • How can I get date and time formats based on Culture Info?
  • How to convert java.util.Date to java.sql.Date?
  • svelte-i18n - Svelte Rollup compiler warning: `this`…
  • Reloading the backbone view and i18n translation…
  • Laravel return home with locale parameter
  • SQL Server FOR EACH Loop
  • Siemens LOGO! PLC data in the wrong order
  • Why is Ember throwing "Uncaught Error: Assertion…
  • Subtracting Dates in Oracle - Number or Interval Datatype?
  • What does "Fatal error: Unexpectedly found nil while…
  • How to iterate (keys, values) in JavaScript?
  • Swift - How to convert String to Double
  • How to solve parse exception when timezone has colon?
  • Composer: The requested PHP extension ext-intl * is…
  • How to show to average sales for each year within…
  • How to use java.net.URLConnection to fire and handle…
  • Webpack: Unable to find module with ID: main --…
  • nextjs error when build production for static website
  • Change app language programmatically in Android
  • Simplest way to create Unix-like continuous pipeline…
  • Formatting a number with exactly two decimals in JavaScript
  • Importing a function from a class in another file?
  • How can I manually compile a svelte component down…
  • Trouble with Next js + Express deployment using Zeit Now
  • Best practice multi language website
  • What's the best way to get the last element of an…
  • Change language on direct url input (VueJs)
  • How to show eras in DateFormat?
  • What does this symbol mean in JavaScript?
  • Use of Jquery on scroll event
  • Invalid date in safari
  • Split string with delimiters in C
  • Does moment.js allow me to derive a timezone…
  • How to format a phone number in a textfield
  • How do I change the language of moment.js?
  • How to obtain the start time and end time of a day?
  • Is it possible to apply CSS to half of a character?
  • How to set level logging to DEBUG in Tomcat?
  • Return datetime object of previous month
  • Get current time in hours and minutes
  • How to print a date in a regular format?
  • Pass props in Link react-router
  • How do I return the response from an asynchronous call?
  • generate days from date range
  • Get a list of dates between two dates using a function
  • What are the undocumented features and limitations…
  • Changing date format in R
  • What is the worst programming language you ever worked with?
  • Round number to nearest integer
  • What's the best way of scraping data from a website?
  • Can I destructure to multiple variables when at…
  • What are the best JVM settings for Eclipse?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Finding the index of an item in a list

Next Post:

For-each over an array in JavaScript

Leave a Reply Cancel reply

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

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error