converting datetime into Date object

时间:2016-08-31 17:29:07

标签: javascript jquery html

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>

2 个答案:

答案 0 :(得分:3)

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="http://momentjs.com/downloads/moment.min.js"></script>

答案 1 :(得分:2)

I believe your problem lies here

var date = new Date(numbers[2], numbers[1], numbers[0]);

You never tell the browser to split for the space in between the date and time. So numbers[2] is going to return 2016 10:40 AM which obviously does not fit the parameters of a new Date object.