Want to get difference between two dates in js? [duplicate] - javascript

This question already has answers here:
Get difference between 2 dates in JavaScript? [duplicate]
(5 answers)
Closed 4 years ago.
I tried so many solution on stack overflow itself, but not get the difference in js.
I was using
var days = ('13-10-2018'- '13-09-2018') / (1000 * 60 * 60 * 24)]

Well, there are 2 issues here.
First, you need to use your date strings to construct a proper JavaScript Date object, which only supports IETF-compliant RFC 2822 timestamps and also a version of ISO8601, as you can see in MDN. Therefore, you can't use DD-MM-YYYY, but you could use MM-DD-YYYY
Another way to construct a Date object is to use this syntax:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
So, to calculate the difference between 2 dates in the format DD-MM-YYYY, you first need to parse that and create two Date objects. Then, you call Date.prototype.getTime() in both of them and calculate the absolute difference in milliseconds. Lastly, you convert that to days dividing by 3600000 * 24 and rounding (if you don't want decimal days):
function getDateFromDDMMYYYY(dateString) {
const [day, month, year] = dateString.split('/');
return new Date(
parseInt(year),
parseInt(month) - 1,
parseInt(day)
);
}
const diff = Math.abs(getDateFromDDMMYYYY('13/10/2018').getTime() - getDateFromDDMMYYYY('13/09/2018').getTime());
const days = Math.round(diff / (3600000 * 24));
console.log(`${ days } ${ days === 1 ? 'day' : 'days' }`);

The way you are trying to subtract dates ('13-10-2018'- '13-09-2018') is wrong. This will give an error NaN (Not a number) because '13-10-2018' for instance is a string and can't be automatically converted to a Date object. if you ask '100' - '20' this will give you 80 as javascript automatically parses a string that can be converted to integers or floats when arithmetic operators are applied but in your case, it's '13-10-2018' that can't be parsed either as an integer or float because parsing it won't give any number.
If the date is in string format then you can parse it in following way and then perform some operation, Since your date is in DD-MM-YYYY I suggest you change it either in MM-DD-YYYY or in YYYY-MM-DD, for more info about Date you can look up to the this link.
let timeDifference = Math.abs(new Date('10-13-2018') - new Date('09-13-2018'));
console.log(Math.ceil( timeDifference / (1000 * 60 * 60 * 24)));
new Date('10-13-2018') - new Date('09-13-2018') will give you 2592000000 milliseconds, since time is represented as Unix time. you can check unix time of any date by doing following.
console.log(new Date().getTime('10-13-2018'));
now the calculations behind the scene is 2592000000 / 1000*60*60*24 (that is total milliseconds in one day) = 30 days

Related

Javascript date to timestamp [duplicate]

This question already has answers here:
Convert normal date to unix timestamp
(12 answers)
Closed last year.
I know there are numerous ways to go about this, but I'm dealing with date formatted as such:
"2021-01-06T16:24:34Z"
How do I convert this to a timestamp that represent post unix epoch with Javascript?
You just need to parse the date, then divide the resulting number by 1000 to have it in seconds.
To parse it, you just need to remove the T and the Z.
let dateString = "2021-01-06T16:24:34Z";
let dateForDateParsing = dateString.replace("T", " ").replace("Z", "");
console.log(dateForDateParsing);
let UnixTimestamp = Math.floor(new Date(dateForDateParsing) / 1000);
console.log(UnixTimestamp);
new Date("2021-01-06T16:24:34Z").getTime() / 1000

Convert getFullYear() in seconds in Javascript

Are there any way to convert the GetFullYear() in real time seconds from the beginning of the current year? Instead of having a output of 2017, i have a dynamic seconds until the end of the year.
As well as obtaining the maximum value of the GetFullYear() converted in seconds to make some calculations.
Thanks in advance
var date1 = new Date("1/1/2017");
var date2 = new Date("2/2/2017");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));//returns 32
var time_in_seconds = diffDays*60*60;// calculate the date in seconds.
Are there any way to convert the GetFullYear() in real time seconds from the beginning of the current year?
To get the difference in milliseconds between two dates, just subtract them. To get ms from the start of the year, subtract now from a date for 1 Jan at 00:00:00, e.g.
function msSinceStartOfYear() {
var now = new Date()
return now - new Date(now.getFullYear(), 0);
}
console.log(msSinceStartOfYear());
As well as obtaining the maximum value of the GetFullYear() converted in seconds to make some calculations.
According to ECMA-262, the maximum time value is 9,007,199,254,740,992, which is approximately 285,616 years after the epoch of 1 Jan 1970, or the year 287,586. So that is the theoretical maximum value of getFullYear.
However:
new Date(9007199254740992)
returns null. The actual range is exactly 100,000,000 days, so to get the maximum value, multiply days by the number of milliseconds per day:
new Date(100000000 * 8.64e7).getUTCFullYear() // 275,760
converted to seconds:
new Date(Date.UTC(275760, 0)) / 1000 // 8,639,977,881,600 seconds
but I have no idea why you want to do that. I've used UTC to remove timezone differences. Using "local" timezone changes the values by the timezone offset.

Javascript : How to calculate the difference between two dates? [duplicate]

This question already has answers here:
Get difference between 2 dates in JavaScript? [duplicate]
(5 answers)
Closed 8 years ago.
How to calculate the difference between two dates say date 1 is 28-04-2014 and date 2 is 30-04-2014 how to find the difference using javascript .
If you are using the datepicker from jQuery UI (or probably any other datepicker tool out there), you can chose what date format you want to recieve. In jQuery UI, use $( "#datepicker" ).datepicker( "option", "dateFormat", "yy-mm-dd" ); to get ISO 8601 dates, and then just compare them like this:
if ( dateOne < dateTwo ) ...
By using a standardized date format, you also know for sure that you will always be able to painlessly convert it to what ever format you want to display it in later.
Vishwas' answer was actually pretty close, even though it's getting downvoted. You need to pass in a valid date format into the new Date() constructor.
var date1 = new Date("28-04-2014".split("-").reverse());
var date2 = new Date("30-04-2014".split("-").reverse());
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays, "number of days difference");
console.log(timeDiff, "in milliseconds");
The Date constructor needs dates in the form new Date(year, month, day, hour, minute etc etc..) and takes arrays too.
Since your date format is in the form day-month-year we take your string and split it (by -) and reverse it to get [year, month, day]
Full Date Object Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Why does the following code not shift the current date forward by five days in JavaScript?

I am learning the Date class in JavaScript and am trying to move the current date forward by five days with the following code:
var today = new Date();
today = today.setDate(today.getDate() + 5);
However, when I run the code I get an extremely long number. Can anyone please explain what I am doing wrong?
This should be enough:
var today = new Date();
today.setDate(today.getDate() + 5);
... as you modify object stored in today anyway with setDate method.
However, with today = in place you assign the result of setDate call to today instead - and that's the number in milliseconds, according to docs:
Date.prototype.setDate(date)
[...]
4. Let u be TimeClip(UTC(newDate)).
5. Set the [[PrimitiveValue]] internal property of this Date object to u.
6. Return u.
Apparently, that number becomes a new value of today, replacing the object stored there before.
The setDate function updates your object with the correct time. You should do
var d = new Date()
d.setDate(d.getDate() + 5);
The d object will have the current date plus five days.
Another way is to use the setTime function. This function accepts as parameter the number of milliseconds since 1969 (the "Epoch" in UNIX time). Correspondingly, the getTime function returns the current date in milliseconds since the Epoch.
To add 5 days to the current date you need to add 5 * 24 * 3600 * 1000, that is, 5 times 24 hours (3600 seconds) times 1000.
var d = new Date()
d.setTime(d.getTime() + 5 * 24 * 3600 * 1000);
Note that your object will be updated and you don't need to watch for the return of neither setTime of setDate.

How to subtract date/time in JavaScript? [duplicate]

This question already has answers here:
How do I get the difference between two Dates in JavaScript?
(18 answers)
Closed 8 years ago.
I have a field at a grid containing date/time and I need to know the difference between that and the current date/time. What could be the best way of doing so?
The dates are stored like "2011-02-07 15:13:06".
This will give you the difference between two dates, in milliseconds
var diff = Math.abs(date1 - date2);
In your example, it'd be
var diff = Math.abs(new Date() - compareDate);
You need to make sure that compareDate is a valid Date object.
Something like this will probably work for you
var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));
i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.
You can just substract two date objects.
var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01"); // some date
var diff = Math.abs(d1-d2); // difference in milliseconds
If you wish to get difference in wall clock time, for local timezone and with day-light saving awareness.
Date.prototype.diffDays = function (date: Date): number {
var utcThis = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
var utcOther = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());
return (utcThis - utcOther) / 86400000;
};
Test
it('diffDays - Czech DST', function () {
// expect this to parse as local time
// with Czech calendar DST change happened 2012-03-25 02:00
var pre = new Date('2012/03/24 03:04:05');
var post = new Date('2012/03/27 03:04:05');
// regardless DST, you still wish to see 3 days
expect(pre.diffDays(post)).toEqual(-3);
});
Diff minutes or seconds is in same fashion.
Unless you are subtracting dates on same browser client and don't care about edge cases like day light saving time changes, you are probably better off using moment.js which offers powerful localized APIs. For example, this is what I have in my utils.js:
subtractDates: function(date1, date2) {
return moment.subtract(date1, date2).milliseconds();
},
millisecondsSince: function(dateSince) {
return moment().subtract(dateSince).milliseconds();
},
You can use getTime() method to convert the Date to the number of milliseconds since January 1, 1970. Then you can easy do any arithmetic operations with the dates. Of course you can convert the number back to the Date with setTime(). See here an example.

Categories

Resources