0

I'm trying to get the diference between 2 dates that look like this:

2018/10/05 13:59

But my issue is with my code, it always retunr NaN.

This is my current code:

var start = '2018/10/05 13:59';
var end = '2018/10/05 17:59';

var converted_start = start.replace("/", "-");
var converted_end = end.replace("/", "-");

// end - start returns difference in milliseconds 
var diff = new Date(converted_end - converted_start);

// get days
var days = diff/1000/60/60/24;

alert(days);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I tried to replace the / with - in my code but that didn't fix the issue!

Could someone please advice on this issue?

Thanks in advance.

James Juanjie
  • 219
  • 3
  • 18
  • I imagine you're first problem is going to be that you are working with strings and trying to subtract them and create a new Date from that result. You are then taking this diff which is meant to be a Date (not sure what it will be at runtime) and then do division on it. I imagine the Date object has methods for doing data manipulation and you should probably look these up – Dave Oct 05 '18 at 13:15
  • @Dave working with strings shouldn't cause any problem. look here: https://stackoverflow.com/questions/2609513/jquery-calculate-day-difference-in-2-date-textboxes – James Juanjie Oct 05 '18 at 13:17
  • @JamesJuanjie seems that that `.val()` returns `Date` object, not string, second snippet in that linked answer contains example – barbsan Oct 05 '18 at 13:21
  • @JamesJuanjie FYI `replace("/", "-")` replaces only first occurence of `/` – barbsan Oct 05 '18 at 13:42
  • @barbsan, thank you... – James Juanjie Oct 05 '18 at 13:44

2 Answers2

2
var start = '2018/10/05 13:59';
var end = '2018/10/05 17:59';

var startDate = Date.parse(start);
var endDate = Date.parse(end);


var diff = new Date(endDate - startDate);

var days = diff/1000/60/60/24;

this works for me

Dave
  • 2,829
  • 3
  • 17
  • 44
0

You can use the following to get days difference in two dates format (YYYY/MM/DD hh:mm):

var start = new Date('2018/10/05 13:59');
var end = new Date('2018/10/05 17:59');

// get hours
var hours= (end-start)/3600000;

alert(hours);
Grant Miller
  • 27,532
  • 16
  • 147
  • 165
Evgeniy Belov
  • 358
  • 1
  • 7
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/21050049) – Dharman Oct 05 '18 at 13:43
  • @Dharman actually it alerts number of hours, this resolves OP's issue but misses `/24` in days calculation – barbsan Oct 05 '18 at 13:51
  • @James Juanjie what is incorrect? this code shows difference in hours. What do you need result? – Evgeniy Belov Oct 05 '18 at 14:58