4

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>
Talha Awan
  • 4,573
  • 4
  • 25
  • 40
Ailyn
  • 265
  • 1
  • 6
  • 17

3 Answers3

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!");
CoderPi
  • 12,985
  • 4
  • 34
  • 62
3

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.com/jsref/jsref_gettime.asp

Ravi Sachaniya
  • 1,641
  • 18
  • 20
  • you don't need to use `getTime()` it's automatically used when doing math operations on an Date object – CoderPi Jun 30 '17 at 06:25
0

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

Charles
  • 1,008
  • 10
  • 21