Transforming various date formats into the en-US format of mm/dd/yyyy hh:mm:ss can be accomplished through JavaScript

When encountering a date format in en-GB or European style (mm.dd.yyyy), it should be converted to the en-US format (mm/dd/yyyy).

If the date is not already in en-US format, then it needs to be converted accordingly.

Answer №1

If you want to format dates in JavaScript, you can utilize the Intl.DateTimeFormat object.

var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));

// Specify the format options
var options = { year: 'numeric', month: 'long', day: 'numeric' };
console.log(new Intl.DateTimeFormat('en-US', options).format(date));
// Result: "December 20, 2012"

For further details and examples, refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat

UPDATE

In response to a user comment, if your date is in a specific format, you will need to parse it before formatting it.

let parse = '29.9.2020 12:09:08'.split(/[.]|:| /);
let date = new Date(Date.UTC(parse[2], parse[1], parse[0], parse[3], parse[4], parse[5]));

var options = { year: 'numeric', month: 'long', day: 'numeric' };
console.log(new Intl.DateTimeFormat('en-US', options).format(date));

After parsing the date into a valid format, you can then proceed with reformatting.

Answer №2

Note: Are non-US date formats ensured to use dots as separators? The convention in en-GB is to utilize slashes, so if a date appears as 10/11/2020, it would be challenging to determine whether this refers to November 10th (en-GB) or October 11th (en-US).


If non-US dates are definitely dot separated, you can employ the following technique:

const dates = [
    '11.10.2020 12:00:00',
    '10/11/2020 13:00:00',
]

const convertToNumbers = str => str
    .split(/\D+/)
    .map(Number)

const process = dateStr => {
    let Y, M, D, h, m, s

    if (dateStr.includes('/')) {
        // assumes en-US format
        [ M, D, Y, h, m, s ] = convertToNumbers(dateStr)
    } else {
        [ D, M, Y, h, m, s ] = convertToNumbers(dateStr)
    }

    // Adjust month index since months start from 0
    return new Date(Y, M - 1, D, h, m, s)
}

// Customize options as necessary
const options = { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false }

const formattedDate = date => {
    return date
        .toLocaleDateString('en-US', options)
}

console.log(dates.map(dateStr => formattedDate(process(dateStr))))

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

Tips on navigating an array to conceal specific items

In my HTML form, there is a functionality where users can click on a plus sign to reveal a list of items, and clicking on a minus sign will hide those items. The code structure is as follows: <div repeat.for="categoryGrouping of categoryDepartm ...

Supporting right-to-left (RTL) localization in Angular 2 and later versions

When it comes to incorporating right-to-left (RTL) support into a localized Angular 2+ application, particularly for languages like Hebrew and Arabic, what is considered the best approach? I have explored various tutorials, including Internationalization ...

Having trouble getting the jQuery function to update text properly

I'm curious to understand the behavior happening in this code snippet. It seems like updating the list item by clicking doesn't work as expected using the initial method. But when rearranging the JavaScript code, it displays the correct value wit ...

retrieve JSON information using jQuery

Hi everyone, I'm trying to figure out how to retrieve JSON data using an AJAX call. I attempted the following method, but it doesn't seem to be working :P First off, I created a JavaScript file where I stored my JSON data: var food = [ ...

Adding style tags dynamically to a component and then encapsulating the styles again (using Angular)

Currently, I am in the process of upgrading from AngularJS to Angular. Our app is currently a hybrid one being bundled up with webpack instead of just angular cli. Due to this setup, we have encountered issues where our css or scss files are not correctly ...

The presence of a default value within an Angular ControlValueAccessor triggers the dirty state due to

My task is to create dynamic Input components for a template driven form using a directive. The default value of the Input component should be set by the component itself. However, I encountered an issue where setting a default value automatically marks t ...

Getting node siblings within an Angular Material nested tree: A comprehensive guide

Struggling to retrieve the list of sibling nodes for a specific Angular Material tree node within a nested tree structure. After exploring the Angular Material official documentation, particularly experimenting with the "Tree with nested nodes," I found t ...

Guide on how to optimize an ajax call in the browser to prefetch JSON data

One scenario I am dealing with involves initiating multiple ajax calls upon page load. The first call fetches data in JSON format from the server, and subsequent user interactions trigger further ajax requests that require database queries to process the J ...

Constructing a regular expression

I've been exploring JavaScript regular expressions and encountering some challenges while trying to build a larger one. Therefore, I have decided to seek help for the entire problem rather than just individual questions. What I am looking for is a re ...

The output returned by an AngularJS controller

John Papa introduced the 'controller as' technique for AngularJS in his article titled Do You Like Your Angular Controllers with or without Sugar: myApp.controller("MainCtrl", [ function () { var vm = this; // using ViewModel conv ...

Decoding JSON data within a Flatlist component in React Native

As a newcomer to React Native, I am currently working on developing an Ecommerce application. For the backend, I am using Woocommerce (Wordpress) and trying to integrate the Woocommerce API response into my React Native App. However, I am facing an issue w ...

When going through an array using jquery, only the final object is returned

I am diving into the world of jQuery and dealing with what seems to be a basic issue. <input type="text" name="text1" value=""></input> <input type="text" name="text2" value=""></input> <input type="text" name="text3" value=""&g ...

fnRedraw and fnReloadAjax do not have the capability to refresh the datatable

I have been working on updating a table with new data from an ajax url. The table loads correctly the first time, but I am struggling to get it to refresh. $(function() { var datepicker = $( "#date-picker" ); var table = $("#reports1").dataTable( ...

Using Angular2, you can dynamically assign values to data-* attributes

In my project, I am looking to create a component that can display different icons based on input. The format required by the icon framework is as follows: <span class="icon icon-generic" data-icon="B"></span> The data-icon="B" attribute sp ...

Arranging titles on the top of the page in a column format, resembling an index

Has anyone figured out how to make the title of the content stick at the top, one below the other, as the user scrolls? I've been using Bootstrap's Scrollspy, which works fine, but I need a few additional features. You can check out the codepen l ...

Angular 10 and Typescript: Variables assigned within the change event become undefined

In my code, I initialize an Algolia input and set an onchange event to it. This initialization takes place in a service. algolia_data; random_var; this.http.post<any>('APIENDPOINT', formData).subscribe(data => { instance = places({ ...

Is the regex returning the correct result?

I need to discuss the date field with a format of YYYYMMDD, as shown below: zod.string().max(8).regex(new RegExp('^(19[0-9][0-9]|20[0-9][0-9]|[0-1][0-9]{3})(1[0-2]|0[1-9])(3[01]|[0-2][1-9]|[12]0)$')); The value provided is 20001915. The definit ...

Determine the previous day's date using JavaScript by subtracting one day

I am facing an issue while attempting to store a specific date format in MongoDB. Instead of saving the date as intended, it is consistently registering a day earlier than specified. For instance - db.test.insert({name: "test1", dob: new Date(1986, 11, ...

Using React and TypeScript to Consume Context with Higher Order Components (HOC)

Trying to incorporate the example Consuming Context with a HOC from React's documentation (React 16.3) into TypeScript (2.8) has been quite challenging for me. Here is the snippet of code provided in the React manual: const ThemeContext = React.creat ...

Bring to the front the div altered by a CSS3 animation

Recently, I encountered an issue with a div card that triggers an animation when clicked. The animation involves the card scaling up larger, but the problem arises as its edges get hidden under other cards. To visualize this, take a look at the screenshot ...