admin管理员组

文章数量:1353122

I am using Eonasdan datetimepicker. In formatting date it contains PM and AM and so I love to use it for my date in order to identify time easily. But when I am creating some condition via Javascript to calculate the total seconds of two given times with AM and PM text it alerts Nan. What is the best solution to get the total number of seconds with AM and PM text given?

The codes are the following:

<script type="text/javascript">
    var datetime_in= '06/30/2017 7:56 AM';
    var datetime_out= '06/30/2017 5:16 PM';

    var totalseconds= datetime_in - datetime_out;
    alert(totalseconds);
</script>

I am using Eonasdan datetimepicker. In formatting date it contains PM and AM and so I love to use it for my date in order to identify time easily. But when I am creating some condition via Javascript to calculate the total seconds of two given times with AM and PM text it alerts Nan. What is the best solution to get the total number of seconds with AM and PM text given?

The codes are the following:

<script type="text/javascript">
    var datetime_in= '06/30/2017 7:56 AM';
    var datetime_out= '06/30/2017 5:16 PM';

    var totalseconds= datetime_in - datetime_out;
    alert(totalseconds);
</script>
Share Improve this question edited Jun 30, 2017 at 7:17 Talha Awan 4,6194 gold badges26 silver badges40 bronze badges asked Jun 30, 2017 at 6:11 AilynAilyn 2952 gold badges6 silver badges17 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

var datetime_in = '06/30/2017 7:56 AM';
var datetime_out = '06/30/2017 5:16 PM';

var totalseconds = Math.abs(new Date(datetime_in) - new Date(datetime_out)) / 1000;
alert("The difference is " + totalseconds + " seconds!");

Use getTime() method.

Return the number of milliseconds since 1970/01/01

    var datetime_in= '06/30/2017 7:56 AM';
    var datetime_out= '06/30/2017 5:16 PM';

    var date_in = new Date(datetime_in);
    var date_out = new Date(datetime_out);
    
    var seconds = Math.abs(date_out.getTime() - date_in.getTime()) / 1000;
    console.log(seconds);

Ref : https://www.w3schools./jsref/jsref_gettime.asp

Use JS Date object and use getTime function in it to get val in milliseconds.

本文标签: htmlGet Total Seconds In javascriptStack Overflow