'Convert month and year into normal date format in reactjs

 <DatePicker onChange={this.dateSelect} value={this.state.dateselected} format={"MM/YYYY"} mode="month" picker="month" disabledDate={(current) => {
                    return moment().add(-4, 'month') >= current;
                }} />

date picker didn't shows the value on edit.. We get date as MM/YYYY format from backend. How to display?



Solution 1:[1]

You need to parse the date components and pass them into the Date() constructor.

const [month, year] = "01/2022".split("/");
const date = new Date(parseInt(year), parseInt(month) - 1);
console.log(date.toString());
// 'Sat Jan 01 2022 00:00:00 GMT-0600 (Central Standard Time)'

Solution 2:[2]

you can convert it via dateformat library for example:

1. npm install dateformat
2. import dateFormat from 'dateformat';
3. dateFormat("2022-03-7T08:59:00.000Z", "mmmm dS, yyyy") to get March 7th, 2022
or dateFormat("2022-03-7T08:59:00.000Z", "dddd, mmmm dS, yyyy") to get Tuesday, March 7th, 2022.

https://www.npmjs.com/package/dateformat

Solution 3:[3]

I think it gives an error is because new Date() function only accepts a specific format YYYY-MM-DD or YYYY/MM/DD so if your Date is not in that format then it will give you an error.

So what you can do is convert your date into a string and pass date, month, year as arguments. You can use the below code for that.

function convertFromStringToDate(responseDate) {
    let dateComponents = responseDate.split('T');
    let datePieces = dateComponents[0].split("-");
    let timePieces = dateComponents[1].split(":");
    return(new Date(datePieces[2], (datePieces[1] - 1), datePieces[0],
                         timePieces[0], timePieces[1], timePieces[2]))
}

convertFromStringToDate("21-03-2020T11:20:30")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 spatialaustin
Solution 2 web developer
Solution 3 Dharmik Patel