krish mandava krish mandava - 1 year ago 54
HTML Question

converting datetime into Date object

How do I convert the below string into a Date object in JavaScript and JQuery and display it.
31/08/2016 10:40 AM

I tried the below approach but it works when I provide only date. I want to work with time too

<div id = "datepicker">31/08/2016</div>

var numbers= $("#datepicker").text().split("/");
var date = new Date(numbers[2], numbers[1], numbers[0]);
document.getElementById("demo4").innerHTML = date

How should I get the Date() object when I provide a div like below

<div id = "datepicker">31/08/2016 10:40 AM</div>

Answer Source

You should look into Moment.js, which is the de-facto standard library for date and time handling in JavaScript.

It is a lot more intuitive and consistent across browsers than JavaScript's native DateTime API:

var myDate = moment("31/08/2016 10:40 AM", "DD/MM/YYYY HH:mm A")
console.log(myDate) // "2016-08-31T14:40:00.000Z"
<script src=""></script>