0

I have called an API and then get a date which is string format like '15/07/21-23:59:59'. But I want to convert this string into the actual date format like this:

**15/07/21** OR **2009-06-01T10:00:00.000**. 

so how can I achieve this?

Manish Kumar
  • 595
  • 2
  • 15
vjtechno
  • 452
  • 1
  • 6
  • 16
  • There are many questions already about [parsing](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+parse+a+date) and [formatting](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+format+a+date) date strings. What have you tried? `'15/07/21-23:59:59'.substring(0,8)` will do for the first example. – RobG Jul 11 '21 at 01:12
  • You might try `new Date(...('15/07/21-23:59:59'.split(/\W/).slice(0,3).reverse().reduce((acc, v, i) => {acc.push(i==0? '20'+v : i==1? --v : v); return acc;}, []))).toLocaleDateString('en-CA')` which gives 2021-07-05. – RobG Jul 12 '21 at 04:46

2 Answers2

0

It's strange to see a response returning a formatted date expression. By the way, your task would be easily done with momentjs. Here is my snippet:

// since your date format is not a standard one, you would have to pass an
// instruction of your date format as a second parameter to the moment constructor
const momentDate = moment('15/07/21-23:59:59', 'DD/MM/YY-HH:mm:ss');

momentDate.format('DD/MM/YYYY'); // => "15/07/2021"
momentDate.format(`yyyy-MM-dd'T'HH:mm:ss.SSSZ`); // => "2021-07-Th'T'23:59:59.000+07:00"
Hunq Vux
  • 35
  • 2
  • 7
-1

you can pass this string to a Date object as follow:

var date = new Date(YOUR STRING); 

or you can use Date.parse() method if it does not work:

Date.parse('04 Dec 1995 00:12:00 GMT');
Abbasihsn
  • 2,075
  • 1
  • 7
  • 17
  • See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Jul 11 '21 at 00:59