1

I have two dates which are in Long string format like "Thu Apr 11 2013 23:59:59 GMT+0530 (India Standard Time)" and I want to take difference between them.

Code :

var x = "Thu Apr 11 2013 23:59:59 GMT+0530 (India Standard Time)"
var today = new Date();
var diff = today.getDate() - x;
alert(diff);
wentjun
  • 40,384
  • 10
  • 95
  • 107
Debashish Dwivedi
  • 327
  • 2
  • 5
  • 13

4 Answers4

3

You can pass date string in to Date(). It will return date object. Then you can find difference.

var date1 = new Date("Thu Apr 11 2013 23:59:59 GMT+0530 (India Standard Time)");
var today = new Date();
var diffTime = Math.abs(today .getTime() - date1.getTime());
var diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
console.log(diffDays);
ZUBAIR V
  • 76
  • 6
1

To find the difference between 2 dates, you should convert both of them into Date objects. This is assuming you want to calculate the difference between the number of days between that day you mentioned on your question and today.

 const x =  new Date("Thu Apr 11 2013 23:59:59 GMT+0530 (India Standard Time)").setHours(0,0,0,0);
 const today = new Date().setHours(0,0,0,0);
 const diff = today - x;
 const oneDay = 24*60*60*1000;
 const result = diff/oneDay;
wentjun
  • 40,384
  • 10
  • 95
  • 107
1

The JS Date() class can parse your string in to a date. The rest is just maths.

var dateFirst = new Date("Thu Apr 11 2013 23:59:59 GMT+0530 (India Standard Time");
var dateSecond = new Date("Thu Apr 12 2013 23:59:59 GMT+0530 (India Standard Time");

 // time difference
 var timeDiff = Math.abs(dateSecond.getTime() - dateFirst.getTime());

 // days difference
 var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

 // difference
 console.log(diffDays);
Charlie
  • 22,886
  • 11
  • 59
  • 90
-1

You can refer following example using moment:

1) Install via NPM dependencies:

npm install moment
2) Import in your Typescript file:

import * as moment from 'moment'
3) Typescript file:
const x =  new Date("Thu Apr 11 2013 23:59:59 GMT+0530 (India Standard Time)")
const today = new Date();
let date1 = moment(x, "DD-MM-YYYY");
let date2 = moment(today, "DD-MM-YYYY"); 
let duration = moment.duration(date1.diff(date2));
let days = duration.asDays();

Moment provides the feature for date difference in many ways.

AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57