Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IST date format to YYYY-MM-DD in javascript

Tags:

javascript

I'm getting a date string "Wed Mar 19 00:30:00 IST 1997" and I want to make this as readable YYYY-MM-DD format. Is there any solution to do this with pure javascript?

like image 737
Nishan Weerasinghe Avatar asked Dec 06 '25 15:12

Nishan Weerasinghe


2 Answers

It seems that your time is not normal javascript date string. if you remove the IST from your string, you can create a date object from it.

dateString = 'Wed Mar 19 00:30:00 IST 1997';
var date = new Date(dateString.replace('IST', ''));

let day = date.getDate();
let month = date.getMonth()+1;
let year = date.getFullYear();

console.log(year+"/"+month+"/"+day)
like image 144
mzfr Avatar answered Dec 09 '25 13:12

mzfr


You can try using the following function

let str = "Wed Mar 19 00:30:00 IST 1997"

function formatDate(date) {
  date = date.split(" ");
  let monthsList = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
  ];

  let year = date[5];
  let month = `0${(monthsList.indexOf(date[1]) + 1)}`.slice(-2);
  let day = date[2];

  return `${year}-${month}-${day}`;
}

console.log(formatDate(str)); 
like image 20
Daniel Rodríguez Meza Avatar answered Dec 09 '25 13:12

Daniel Rodríguez Meza