Home > OS >  Date from string treated as wrong format
Date from string treated as wrong format

Time:12-29

I had a string value = "01/08/2021 - 31/08/2021" and i need to get the starting date using value.substring(0,10) which return as 01/08/2021. But when i converting it to date using new Date(value.substring(0,10)) it convert the date format as 2021-01-08(yyyy-mm-dd).

Any help on this ?

CodePudding user response:

Split into the year, month and day

const [day, month, year] = value.substring(0,10).split('/');

Use the Date constructor

new Date(year, month - 1, day);

CodePudding user response:

JavaScript date decodes your date string to "mm/dd/yyyy" format. You can simply split your date string to month - mm, date - dd and year - yyyy and provide this to date object.

Please Note: Dont forget to reduce 1 from the month number. Because JavaScript date counts month from 0 to 11.

const value = "01/08/2021 - 31/08/2021";
//  const startDate = value.substring(0,10);
const [startDate, endDate] = value.split(" - ");
const [dd, mm, yyyy] = startDate.split("/");
console.log(startDate);
console.log(new Date(yyyy,  mm - 1, dd).toDateString());

CodePudding user response:

There's a library for conversion:

npm install dateformat

Then write your requirement:

var dateFormat = require('dateformat');

Then bind the value:

var day=dateFormat(new Date(value.substring(0,10)), "dd-mm-yyyy");

https://github.com/felixge/node-dateformat

  • Related