Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Convert String ' dd/mm/yy hh:MM:ss ' to Date in javascript?

I have Done this

    var d='dd/mm/yy hh:MM:ss';
    var d1=d.split(" ");
    var date=d1[0].split("/");
    var time=d1[1].split(":");
    var dd=date[0];
    var mm=date[1]-1;
    var yy=date[2];
    var hh=time[0];
    var min=time[1];
    var ss=time[2];
    var fromdt= new Date("20"+yy,mm-1,dd,hh,min,ss);

Is there Any way to do it using JQuery OR JavaScript?

like image 758
Kumar Avatar asked Jun 17 '15 12:06

Kumar


2 Answers

This will work regardless of timezone for the format dd/mm/yyy hh:mm:ss only. It also does not rely on third party packages:

let dtStr = "12/03/2010 09:55:35"

console.log(strToDate(dtStr));  // Fri Mar 12 2010 09:55:35

function strToDate(dtStr) {
  if (!dtStr) return null
  let dateParts = dtStr.split("/");
  let timeParts = dateParts[2].split(" ")[1].split(":");
  dateParts[2] = dateParts[2].split(" ")[0];
  // month is 0-based, that's why we need dataParts[1] - 1
  return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1], timeParts[2]);
}
like image 138
Sean Coley Avatar answered Oct 03 '22 07:10

Sean Coley


If you are looking for alternatives in jquery or Javascript , then you can go with Moment.js,where you can Parse, Validate, Manipulate, and Display dates in JavaScript.

example:

  var date= moment("06/06/2015 11:11:11").format('DD-MMM-YYYY');
like image 35
ANR Upgraded Version Avatar answered Oct 03 '22 06:10

ANR Upgraded Version