What is the process for configuring the locale when parsing in moment.js?

I was unable to find the answer in the documentation, so...

Consider this scenario: I have an input date of "09/01/2017". It could be either DD/MM/YYYY or MM/DD/YYYY format based on user locale. Is there a way to achieve something like this?

let date   = "09/01/2017",
    locale = "en_US", // or "en_AU"
    result = moment(date, locale).format("DD MMM YYYY");
// 01 Sep 2017
// 09 Jan 2017

Alternatively, should I create a map and then assign a format to moment?

let map =
    {
        en_US: 'DD/MM/YYYY',
        en_AU: 'MM/DD/YYYY',
        // ...
    },
    date   = "09/01/2017",
    locale = "en_US",// or "en_AU"
    result = moment(date, map[locale]).format("DD MMM YYYY");
// 01 Sep 2017
// 09 Jan 2017

Thank you.

Answer №1

To obtain locale specific tokens, you can utilize the moment.localeData() method along with longDateFormat('L').

Below is a demonstration:

let date   = "09/01/2017";
let locale = "en_US";
let localeFormat =  moment.localeData(locale).longDateFormat('L');
let result = moment(date, localeFormat).format("DD MMM YYYY");
console.log(result); // 01 Sep 2017

locale = "en_AU";
localeFormat =  moment.localeData(locale).longDateFormat('L');
result = moment(date, localeFormat).format("DD MMM YYYY");
console.log(result); // 09 Jan 2017
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>

Answer №2

To extract the month from a local date, I would rely on vanilla JavaScript to get the month based on the locale. Then, I would utilize moment.js to format the month into MMM format before combining them together.

var locale = 'en_AU'

var date = '09/01/2019'.split('/')

if (locale === 'en_AU') {
    var monthFormatted = moment(date[0]).format('MMM')
    date = [date[1], monthFormatted, date[2]].join(' ')
}

else {
    var monthFormatted = moment(date[1]).format('MMM')
    date = [date[0], monthFormatted, date[2]].join(' ')
}

console.log(date)
// 09 Jan 2019 or 01 Sep 2019

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why isn't my function being triggered by the Click event?

I can't figure out why the click event isn't triggering the btn() function. function btn() { var radio = document.getElementsByTagName("input"); for (var i = 0; i > radio.length; i++){ if (radio[i].checked){ alert(radio[i].value); } ...

Access the configuration of a web browser

I am in the process of creating a website where I need to prompt the user to enable JavaScript. Is there a way for me to include a link to the browser's settings page? Here is an example: <noscript> <div>Please enable JavaScript &l ...

What is the best way to modify items in an array when the desired field name is stored in a variable?

I am facing a challenge in organizing the data structure for efficient updates with minimal server load. When a user clicks on "add", an object is inserted without any values on the UI. Meteor.methods({ addExp: function() { var expDoc = { obj ...

Mastering the proper utilization of document.readyState in conjunction with Selenium

I am exploring a method to automatically scroll down a page that loads content dynamically as it is scrolled, ensuring everything is loaded before interacting with it using Selenium. I came across this code originally written for c#, which I have converte ...

Is it guaranteed that ajax will execute during beforeunload event?

I am developing an HTML5 application and I need to send a disconnect ajax request when the user changes or refreshes the page. Currently, I have implemented this code: window.addEventListener("beforeunload", function(event) { $.ajax({ url: api ...

Tips on how to dynamically load the content of a URL into a modal and update the browser address simultaneously

I am attempting to achieve a specific effect using JavaScript and jQuery Link to the content I want to load in a modal The goal is to load the content in a modal while keeping the main page in the background. Additionally, when a URL is followed, I want ...

Using two loops/arrays in JavaScript to generate a rating score

I want to create a simple rating component with the following appearance: ◼◼◼◻◻ (score: 3 out of 5) Here is my JSX code snippet: var score = 3; var range = 5; { [...Array(range)].map((e, i) => ( <div className="rating-item" ...

What is the best way to identify duplicate data being returned from a server within a for loop?

When receiving sorted data from the server through an infinite scroll, my goal is to filter out duplicate entries and add new unique data to a client-side array. If duplicates are found, I want to stop the infinite scrolling process. $scope.collections = ...

Navigating a JavaScript Array of Objects, Deleting Elements

In my Vue and Rails project, I am facing an issue with removing text from input fields when users switch between adding a new recipe and going back to the main page. While this functionality works for all fields except for ingredients, I am specifically st ...

Error message: "Link binding error in knockout collection"

In this example, you'll find my Knockout ViewModel. $(document).ready( function () { var Incident = function (CaseNumber, DateOfIncident, Description) { this.CaseNumber = CaseNumber; this.DateOfIncident = DateOfIn ...

The Javascript setTimeout Function Prolongs Its Operation

Currently, I have a web app index page that performs two main tasks. Firstly, it geocodes the user's location and stores it in a JavaScript variable called "variableToSend." Secondly, it sends this data to mySQL using a PHP script after a delay of 10 ...

Is it possible to create tabs using Ajax without using jQuery?

Exploring the realm of tabs that dynamically load content into a div without redirecting to another page unveils numerous possibilities. Although the existing examples mostly rely on ajax with jQuery or similar libraries, I am inclined towards exploring a ...

What is the process for incorporating an npm package into an HTML document?

Here is the code from my HTML file: <!DOCTYPE html> <head> ... </head> <body> ... <script src="script.js"></script> </body> This is what I have in my JavaScript file named script.js: import * as File ...

What causes Spyscroll to be impacted by Collapse in Bootstrap 5?

I'm utilizing bootstrap 5 as my CSS framework and currently working on a significant section. Therefore, I chose to structure it with one row containing four columns, hiding the others using Bootstrap's collapse feature. However, because this is ...

Exploring the wonders of useState in React/JavaScript - a comprehensive guide

I encountered an issue while attempting to map an API request from a useState hook. The fetch operation functions correctly and returns an array of objects that I then assign to my useState variable. Subsequently, when I try to map over the useState varia ...

Utilizing Ajax looping to generate dynamic HTML content with Bootstrap tabs

I am looking for a way to fetch multiple JSON files and display the data from each file in separate Bootstrap 3 Tabs. I understand that the getJSON function does not wait for completion before moving on, but I need help with using callbacks in situations ...

Using Vanilla JavaScript and VueJS to smoothly scroll back to the top of a div when a button is clicked

I have a VueJS-based app that features a multistep form with a next button. You can check out the functioning of the app here: My current challenge is ensuring that once the user clicks the next button, the top of the following question becomes visible. I ...

Troubleshooting Sequelize's hasMany and belongsTo relationships

Looking to create 2 tables in Mysql using the power of node.js & sequelize.js. The two models we're working with are User and Company Here's what the fields for User look like: - id - username - password And for Company, here are its fields: - ...

Navigating through the text in between search restrictions of lookbehind and lookahead can be

Below is the text I am working with. Hello my name is Adam (age: 25) I live in US. Hello my name is Bill (age: 23) I live in Asia. I am trying to extract the age and location using lookahead and lookbehind. The desired output format should be as follows ...

Tips on concealing the divs following the second click and a page refresh

Bootstrap 4 js collapse is working fine, but I am facing an issue. When I click to show a hidden div and then reload the page, clicking again reveals the previously hidden div when it should be hidden. Any suggestions for addressing this problem? ...