In need of changing the date format post splitting

I need help converting a date from MM/DD/YY to YYYYMMDD

The current code I have is giving me an incorrect output of 2211. How can I implement a check on the Month and Day values to add a leading zero when necessary?

var arr = '1/1/22';
arr = NTE.split('/');  //this splits the date at each /
log.debug("Splitting date : "+ arr);
        
longDate=arr[2]+arr[0]+arr[1];   
log.debug("Long Date : "+ longDate);

Answer №1

If you are looking to reformat a date, consider trying the following code snippet:

let date = '1/1/22';
date = date.split('/');  //splitting the date by '/'
console.log("Split Date: " + date);

date = date.map((elem) => elem.length > 1 ? elem : `0${elem}`); // add leading zero if necessary
const newDate = `20${date[2]}${date[0]}${date[1]}`; //prepend year with 20 for YYYY format
console.log("New Date Format: " + newDate);

Answer №2

const inputDate = '1/1/22';

let arr = inputDate.split('/');  //splits the date where it finds /
console.log('Splitting date:', arr);

let dayEdited = false;
let monthEdited = false;
let yearEdited = false;

if (arr[0] < 10) {
    arr[0] = "0" + arr[0];
    console.log('add zero to month:', arr[0]);
    dayEdited = true;
}

if (arr[1] < 10) {
    arr[1] = "0" + arr[1];
    console.log('add zero to day:', arr[1]);
    monthEdited = true;
}

if (arr[2] < 2000) {
    arr[2] = "20" + arr[2];
    console.log('add 20 to Year:', arr[2]);
    yearEdited = true;
}

if (yearEdited && monthEdited && dayEdited) {
    let longerDate = arr[2] + arr[0] + arr[1] + "000000";    //rearranges the array by YEAR, MONTH, DAY
    console.log('Longer Date:', longerDate);
} else if (!yearEdited && monthEdited && dayEdited) {
    let longerDate = arr[2] + arr[0] + arr[1] + "000000";    //rearranges the array by YEAR, MONTH, DAY
    console.log('Longer Date :', longerDate);
} else if (!yearEdited && !monthEdited && dayEdited) {
    let longerDate = arr[2] + arr[0] + arr[1] + "000000";    //rearranges the array by YEAR, MONTH, DAY
    console.log('Longer Date:', longerDate);
} else if (!yearEdited && monthEdited && !dayEdited) {
    let longerDate = arr[2] + arr[0] + arr[1] + "000000";    //rearranges the array by YEAR, MONTH, DAY
    console.log('Longer Date:', longerDate);    
} else if (yearEdited && !monthEdited && !dayEdited) {
    let longerDate = arr[2] + arr[0] + arr[1] + "000000";    //rearranges the array by YEAR, MONTH, DAY
    console.log('Longer Date:', longerDate);
} else if (!yearEdited && !monthEdited && !dayEdited) {
    let longerDate = arr[2] + arr[0] + arr[1] + "000000";    //rearranges the array by YEAR, MONTH, DAY
    console.log('Longer Date:', longerDate);
}

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

I am interested in utilizing Maven and paulhammant (Selenium_java) to input text into a textefield

When attempting to write in the text field using selenium, I encountered an error stating "unexpected identifier". Any assistance with this issue would be appreciated. See image for more details ...

problem with creating a django template script

Hello, I am currently working on a code that is responsible for executing various functions within the template. I have utilized scripts to verify these functions using if-else statements and for loops. However, I am encountering some errors during this pr ...

Encountering a mysterious error while attempting to access and modify a value stored in a useState hook using the keydown

I've been attempting to create a simple animation on canvas using React.js, but I'm facing an issue with integrating my Keydown function with my useState. It seems that my useState value is not being defined properly, preventing me from changing ...

Exploring the features of useEffect and setState in hook functions

Exploring the idea of utilizing React to efficiently fetch data using useEffect correctly. Currently facing a situation where data fetching is occurring constantly instead of just once and updating only when there is an input for the date period (triggeri ...

Place a request for the Material UI switch on the platform

I'm currently in the process of constructing a switch that gets its checked value from the data retrieved from the backend. When a user toggles it, a PUT request is sent to the backend for updating the choice. Although I've made progress on it, ...

Error: Cannot execute 'x' as a function

I am currently developing an Express web application that initiates JavaScript scraping code upon the page's initial load. Below is the node web scraping code (scrape.js): const request = require('request-promise'); const cheerio = require( ...

Tips on displaying a confirmation message upon a user clicking a checkbox

I am encountering an issue with displaying a confirmation message when a checkbox is clicked. The confirmation box pops up but does not carry out any action, like showing the text within the textbox after the user clicks OK. Any guidance on this matter wou ...

Is there a way to retrieve the JSON url from the input box

My goal is to retrieve a JSON file from a URL entered in a text box. I have identified the text box as txtr and used jQuery to get the value like this: var txtbval = $("#txtr").val();. I then included this value in the JSON parsing script as follows: url: ...

What are effective ways to eliminate cross-origin request restrictions in Chrome?

Just starting out with angular and trying to incorporate a templateUrl in an angular directive. However, when attempting to view the local html file in the browser, I encounter the following errors --> XMLHttpRequest cannot load file:///Users/suparnade ...

I need to find a way to identify when empty JSON data is being submitted to my RESTful HTTP POST endpoint. This issue is causing

I've set up a REST endpoint to handle JSON data sent via an HTTP post request using XMLHttpRequest as my client. Everything seems to be working smoothly until I wanted to test how the server would handle receiving no data at all, specifically null. To ...

Calculate a value within a MongoDB field

Hello everyone, I have a document in my collection that looks like this: { Player_Name: Sandeep Nair Player_TotalWeightedPoints: 80 Player_Rank: 23 } I have around 200 similar documents in my collection. The Player_Rank is determined by the total Weighted ...

Is there a way to effectively organize an RSS feed using the .isoDate parameter while ensuring that the feed's elements remain interconnected (such as title and link)?

My goal is to organize the RSS feed by the most recent item while ensuring that each title corresponds correctly with its link. Currently, I am parsing and displaying the feed using the .isoDate property, but I am unsure of the best approach to achieve thi ...

What techniques can be used to avoid the MUI `DataGrid` from constantly re-rendering when a row is committed?

Check it out here to see how the MUI documentation implemented it: <b>const</b> rows = [/* Row Data */] <DataGrid rows={rows} {/* Other Props */} /> <sup>/*[1]*/</sup> The approach taken by MUI is quite impressive. It streaml ...

displaying a confirmation using jQuery in CodeIgniter

Hello everyone, I am a beginner in CodeIgniter and I am seeking assistance. I am attempting to create a confirmation message (div id="delmsg") using jQuery when deleting a record from MySQL database. The delete operation is functioning properly, but the me ...

Running the command Yarn build with Vite.js and React.js is encountering issues and is not functioning properly

Lately, I've been experimenting with Vite in my React projects. However, when I execute the command yarn build, it creates a Build folder but the application fails to work. When I open the index.html file, all I see is a blank page. Interestingly, e ...

Displaying an array of objects in the MUI Datagrid interface

I have integrated Redux into my project to retrieve data from the API, and this is a snapshot of the data structure: https://i.stack.imgur.com/jMjUF.png My current challenge lies in finding an effective way to display the information stored within the &a ...

Is there a method to make this package compatible with Angular version 16?

I recently integrated the ngx-hotjar package version 11.0.0 into my Angular 10 project with success. However, when trying to use it in a new Angular 16 project, I encountered the following error during ng serve: Error: src/app/app.module.ts:275:12 - error ...

Understanding the syntax for matching files and paths in Node/JavaScript using glob, including the use of wild

I stumbled upon http://gruntjs.com/configuring-tasks#globbing-patterns and found it to be the most useful reference so far. I have come across the following statement multiple times: For more on glob pattern syntax, see the node-glob and minimatch docu ...

How can you retrieve the index of the outer repeater item within nested ng-repeaters in AngularJS?

If I have multiple ng-repeat loops nested within each other like in the following example: <div ng-repeat="outeritem in outerobject"> <div ng-repeat="inneritem in innerobject" ng-click="function(inneritem.key, $index)"></div> <d ...

Divide Chinese Characters

Is there a way to split foreign characters like Chinese into separate array values using JavaScript? While the split() function works well with English, it doesn't seem to handle Chinese characters properly. Take a look at the results from two string ...