0

I have date string in the format '2020/02/25 23:58:08' . I want to parse it to '2020-02-25".

Note : Initially date is in string format, after conversion whether it is in date or string format it doesn't matter.

file.js

   function test (filepath) {

    let date = "2020/02/25 23:58:08";
    date = date.replace("//"/gi,"-");
   // I am not familiar with regular expressions, I want to omit the data related to hours, seconds extra   
   }

When I ran the program, I gotUncaught ReferenceError: gi is not defined, gi is to globally replace

karansys
  • 2,449
  • 7
  • 40
  • 78

3 Answers3

2

Try this

let date = "2020/02/25 23:58:08";
var date2 = new Date(date)
console.log(date2.toISOString().slice(0,10))
Bardales
  • 304
  • 1
  • 4
  • 14
1

let date = `2020/02/25 23:58:08`;
let parsedDate = date.split(" ")[0].replace(/\//gi,'-');
console.log(parsedDate);
Akshay Bande
  • 2,491
  • 2
  • 12
  • 29
1

There is an error in the line using regex, should be:

let date = "2020/02/25 23:58:08";
date = date.replace(/\//gi,"-");

Then to get only the date, you can get the first 10 characters:

date.slice(0,10)

Final code:

let date = "2020/02/25 23:58:08";
date = date.replace(/\//gi,"-");
date.slice(0,10)

Although there are other ways to do it, you can use a library like momentJs which includes methods for this, like moment.format, it gives so many possibilities. But if you have a small case this is fine.

elhoucine
  • 2,356
  • 4
  • 21
  • 37