Convert the Date FR and Date US formats to ISO date format

There is a function in my code that accepts dates in different formats. It can handle two formats:

2022-06-04

or

04/06/2022

I want all dates to be in the format:

2022-06-04

For instance:

public getMaxduration(data: object[]): number {


 data.forEach((line) => {
  const periodFrom = new Date(line['period_to'];
  const periodTo = new Date(line['period_from'];

  console.log(periodFrom);
  console.log(periodTo);

 })

}

The issue I'm facing is when a date is provided in the dd/mm/yyyy format, it causes problems. How can I ensure all dates within this function are formatted as yyyy-mm-dd?

Answer №1

To effectively handle different input formats, one approach is to utilize regular expressions to determine the format before creating an array containing [year, month, day] values extracted from the input string using String.split(). In cases where the input date follows the pattern day/month/year, a reversal of the array is performed to ensure correct values are obtained.

After obtaining year, month, and day values, the map function along with join is employed to generate the desired output format.

function reformatDate(input) {
    let arr = [];
    if (/\d{4}-\d{1,2}-\d{1,2}/.test(input)) {
        arr = input.split('-'); // yyyy-M-d
    } else if (/\d{1,2}\/\d{1,2}\/\d{4}/.test(input)) {
        arr = input.split('/').reverse(); // d/M/yyyy
    } else {
        throw new Error('Unknown date format:', input);
    }
    return arr.map(str => str.padStart(2, '0')).join('-');
}

const dates = ['2022-10-18', '2022-08-23', '18/10/2022', '31/2/2019'];

console.log('Input'.padEnd(12), 'Output')
dates.forEach(date => { 
    console.log(date.padEnd(12), reformatDate(date))
})

Answer №2

There are two approaches you can take:

1. Utilize the moment library:

return moment(new Date(dateInput)).format('YYYY-MM-DD');

2. Alternatively, you can achieve the same result with the following code snippet:

const date = new Date(dateInput);
return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();

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 for successfully retrieving a boolean value from an ASP.Net JavaScript AJAX request using a C# method

Query: Is there a way to call a C# function from JavaScript code on an .aspx webpage to get authentication results based on a username and password? Here is the JavaScript AJAX POST request I am currently using: $.ajax({ type: "POST", ...

Having trouble converting JSON into a JavaScript object

I am encountering an issue with my HTML box: <span>Select department</span><span> <select id="department" onchange="EnableSlaveSelectBox(this)" data-slaveelaments='{"a": 1, "b": "2& ...

angular and node: troubleshooting the $http.get error

I have encountered an issue with the $http.get instruction. Without it on the main page, I receive a result of "random 46" which is correct. However, when I include $http.get, I get a result of "random {{ number }}". How can this problem be resolved? -se ...

Encountering a 500 internal server error while trying to submit a form via AJAX and

I'm a beginner in PHP and I'm facing issues with sending test emails from my local host. My form consists of 3 fields, and I want the user to be able to submit the form and see a success message without the page refreshing. Although I have set u ...

Return either a wrapped or base type based on the condition

I am a beginner in TypeScript and I'm struggling to find the right combination of search terms to solve my issue. It seems like using a type condition could be helpful, but I still need to grasp how they function. My goal is to pass a function that p ...

The system encountered an issue while trying to access the property 'emailVerified' of an undefined object

I am currently working on retrieving the current user and attempting to assign the user values to a getter. In the constructor, I can see in the console that it is returning "email verified" as true. However, when trying to set it in the getter, I am enc ...

Concealing and revealing template URLs with AngularJS

I am currently working with a dynamic Array in my Controller that contains templates (html files) structured similarly to the example below: $scope.templates = [ { name: 'template1.html', url: 'template1.html'}, { name: ...

Fetching information via AJAX to populate a whitelist for Tagify

Attempting to retrieve data via ajax for tagify whitelist, but encountering the following error: ReferenceError: Can't find variable: clist Here is the code snippet: $.ajax({ url: '/ajaxget/tags', method: &ap ...

Searching Firestore arrays for objects based on one of two fields

Within my document, I am working with the following array: I have a SizeFilterComponent that emits a BaseFilter object when a size is selected. Multiple sizes can be selected. Here is the method handling this logic: selectionChange($event){ let array ...

Passing Parent Method to Child Component in React Native

I'm experiencing an issue trying to pass a method from my parent component to a child component. Although I believe my code is correct, I keep getting the error message undefined is not an object(evaluating '_this2.props.updateData'). Despit ...

Utilizing Filepond to extract base64 data in a React JS environment

Struggling to extract a base64 from an image upload and send it along with other values to the server. Due to API limitations allowing only 2 files at a time, I'm unable to process uploads individually. Having difficulty in mapping the 'data&apo ...

javascript image alert

I want to upgrade a basic javascript alert to make it look more visually appealing. Currently, the alert is generated using if(isset($_GET['return'])) { // get a random item $sql = "SELECT * FROM pp_undergroundItems AS u LEFT JO ...

Using an iframe containing a link to trigger the opening of a colorbox in the

Recently, I encountered a challenge regarding an iframe containing a bar graph. I wanted to achieve that when the graph is clicked, it would open a colorbox with a more detailed graph from the "PARENT" of that iframe. Initially, I managed to get the ifram ...

Steps to dynamically set the value of an input type="time" using JavaScript

Despite the repetitive nature of these questions, I have yet to find a solution to my specific query. Any help would be greatly appreciated. Thank you in advance. The HTML code is as follows: var start="10:30 PM"; $scope.edit={} frtime=start.split("PM ...

When a new element is added to the DOM, bind a click event to it that will trigger another

When I add an element to the DOM, I bind it with a click function. The problem is that if I add multiple elements and click on any of them, the function triggers multiple times. What causes this behavior and is there a better way to achieve the desired res ...

Tips on ensuring Angular calls you back once the view is ready

My issue arises when I update a dropdown list on one of my pages and need to trigger a refresh method on this dropdown upon updating the items. Unfortunately, I am unsure how to capture an event for this specific scenario. It seems like enlisting Angular ...

"Trouble with Angular JS foreach loop: only the final item in the array

Struggling to loop through each item object in a JSON data set and evaluate its value using angular.forEach(). However, only the last item is being returned, making it impossible to perform any meaningful evaluation. Oddly enough, when using console.log(), ...

Individualize JavaScript clients for each module in ExpressJS

Exploring the modular folder structure demonstrated by tjholowaychuk in this video. Is there a way to include a distinct client-side JavaScript file within each module? Currently, all my client JS resides in the /assets/js folder, but having a separate JS ...

Adding a class using jQuery based on whether a section is visible or hidden on the screen

Seeking advice on the best approach to take. Division 1 or section - Apply style 1 if division 1 is currently visible on the screen. Division 2 or section - Apply style 1 if division 2 is currently visible on the screen. Division 3 or section - Apply st ...

Introduction to React with Typescript: Greeting the World

I am attempting to create a Hello World React application with Typescript. Below is the code I have written. Method 1 works without any issues, but method 2 throws an error. Method 1 - TypeScriptComponent.tsx import React from 'react' import Re ...