get date difference in javascript - javascript

I want to get the difference of of these dates.
e.g
var current_date = new Date();
var date_from_database = "2013/06/10 15:00:00";
var difference = data_from_datebase - current_date;
// so the result should be: 7
I want to get how many days left buy subtracting the current day on specific day like the example above. How can I do this on javascript?
Thanks in advance!

The following might work:
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

var date_from_database = new Date("2013/06/10 15:00:00");
var date1= new Date();
var date_diff = Math.abs(date2.getTime() - date_from_database .getTime()/86400000);

In order to compare it with the current day:
var firstDate = new Date(2008,01,12);
var secondDate = new Date();
var timeDiff = Math.abs(firstDate.getTime() - secondDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
http://jsfiddle.net/imac/TEjqX/
You will have to modify the date you receive from the database to addapt it to the needed parameter for date().
You can take a look at this answer for more info.

Javascript could be very pesky in processing the datetime variables.
Do not reinvent the wheel. I often use the datejs library.
In particular, the time.js file features the TimeSpan() function that processes datetime differences.
References:
date.js main page
date.js # google code
time.js page

Related

Difference between two date in seconds [duplicate]

I'm trying to get a difference between two dates in seconds. The logic would be like this :
set an initial date which would be now;
set a final date which would be the initial date plus some amount of seconds in future ( let's say 15 for instance )
get the difference between those two ( the amount of seconds )
The reason why I'm doing it it with dates it's because the final date / time depends on some other variables and it's never the same ( it depends on how fast a user does something ) and I also store the initial date for other things.
I've been trying something like this :
var _initial = new Date(),
_initial = _initial.setDate(_initial.getDate()),
_final = new Date(_initial);
_final = _final.setDate(_final.getDate() + 15 / 1000 * 60);
var dif = Math.round((_final - _initial) / (1000 * 60));
The thing is that I never get the right difference. I tried dividing by 24 * 60 which would leave me with the seconds, but I never get it right. So what is it wrong with my logic ? I might be making some stupid mistake as it's quite late, but it bothers me that I cannot get it to work :)
The Code
var startDate = new Date();
// Do your operations
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;
Or even simpler (endDate - startDate) / 1000 as pointed out in the comments unless you're using typescript.
The explanation
You need to call the getTime() method for the Date objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate() method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime() method, representing the number of milliseconds since January 1st 1970, 00:00
Rant
Depending on what your date related operations are, you might want to invest in integrating a library such as day.js or Luxon which make things so much easier for the developer, but that's just a matter of personal preference.
For example in Luxon we would do t1.diff(t2, "seconds") which is beautiful.
Useful docs for this answer
Why 1970?
Date object
Date's getTime method
Date's getDate method
Need more accuracy than just seconds?
You can use new Date().getTime() for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms into s.
const start = new Date().getTime();
const end = new Date().getTime();
const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);
Below code will give the time difference in second.
import Foundation
var date1 = new Date(); // current date
var date2 = new Date("06/26/2018"); // mm/dd/yyyy format
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // in miliseconds
var timeDiffInSecond = Math.ceil(timeDiff / 1000); // in second
alert(timeDiffInSecond );
<script type="text/javascript">
var _initial = '2015-05-21T10:17:28.593Z';
var fromTime = new Date(_initial);
var toTime = new Date();
var differenceTravel = toTime.getTime() - fromTime.getTime();
var seconds = Math.floor((differenceTravel) / (1000));
document.write('+ seconds +');
</script>
Accurate and fast will give output in seconds:
let startDate = new Date()
let endDate = new Date("yyyy-MM-dd'T'HH:mm:ssZ");
let seconds = Math.round((endDate.getTime() - startDate.getTime()) / 1000);
time difference between now and 10 minutes later using momentjs
let start_time = moment().format('YYYY-MM-DD HH:mm:ss');
let next_time = moment().add(10, 'm').format('YYYY-MM-DD HH:mm:ss');
let diff_milliseconds = Date.parse(next_time) - Date.parse(star_time);
let diff_seconds = diff_milliseconds * 1000;
let startTime = new Date(timeStamp1);
let endTime = new Date(timeStamp2);
to get the difference between the dates in seconds ->
let timeDiffInSeconds = Math.floor((endTime - startTime) / 1000);
but this porduces results in utc(for some reason that i dont know).
So you have to take account for timezone offset, which you can do so by adding
new Date().getTimezoneOffset();
but this gives timezone offset in minutes, so you have to multiply it by 60 to get the difference in seconds.
let timeDiffInSecondsWithTZOffset = timeDiffInSeconds + (new Date().getTimezoneOffset() * 60);
This will produce result which is correct according to any timezone & wont add/subtract hours based on your timezone relative to utc.
Define two dates using new Date().
Calculate the time difference of two dates using date2. getTime() – date1. getTime();
Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (10006060*24)
const getTimeBetweenDates = (startDate, endDate) => {
const seconds = Math.floor((endDate - startDate) / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
return { seconds, minutes, hours, days };
};
try using dedicated functions from high level programming languages. JavaScript .getSeconds(); suits here:
var specifiedTime = new Date("November 02, 2017 06:00:00");
var specifiedTimeSeconds = specifiedTime.getSeconds();
var currentTime = new Date();
var currentTimeSeconds = currentTime.getSeconds();
alert(specifiedTimeSeconds-currentTimeSeconds);

Javascript check two dates

Code:
var fromDate = new Date('2015-05-21T10:17:28.593Z')
var endDate = new Date()
I have from date and end date.How to check from date is ascending or descending than end date?.any help will be appreicated.thanks in advance
From my understanding you are trying to check if fromDate is later than endDate. You can just use the standard comparison operator and it will work just fine.
var fromDate = new Date('2015-05-21T10:17:28.593Z').getTime();
var endDate = new Date().getTime();
var isFromDateAscending = fromDate > endDate;
console.log(isFromDateAscending);
You can simply do :
var fromDate = new Date('2015-05-21T10:17:28.593Z')
var endDate = new Date()
if (fromDate > endDate) {
alert("FromDate is Ascending")
}else{
alert("EndDate is Ascending")
}
I would be using MomentJS for date checking/parsing/manipulation as it has a very good API and helps deal with unexpected hitches that the native Date interface can expose.
//Import moment
import * as moment from 'moment';
//In your file somewhere
if (moment().isAfter(moment('2015-05-21T10:17:28.593Z'))) {
//Current time is after the fromDate
} else {
//fromDate is after current time
}
It also has a bunch of display utilities etc. that can help when dealing with times (and timezones). You can check the documentation here
var date1 = new Date("7/11/2010");
var date2 = new Date("8/11/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24));
alert(diffDays )
diffDays is the answer u desire

Check if date is within X number of days of today

I have a date variable being set on my page like this:
startDate = "03/28/2017";
How can I check if that date is 7 or less days before today's date?
It will need to be used in a conditional if statement.
You can try using moment.js,
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
or even better, it has an inbuilt method, which says after how many days.
moment([2007, 0, 29]).toNow(); // in 4 years
and if you want to use old plain javascript :
var date1 = new Date("3/30/2017");
var date2 = new Date("3/23/2017");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
If you want to compare with today
var date1 = new Date("3/23/2017")
var date2 = new Date();

how to insert current date in html script

I have the current script. var date 2 needs to automatically grab the current date and then do the calculation. I have tried many things with no luck, please help.
<script>
// Here are the two dates to compare
var date1 = '2015-09-08';
var date2 = '2015-12-13';
// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');
// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1], date1[2]);
date2 = new Date(date2[0], date2[1], date2[2]);
// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime() / 1000);
date2_unixtime = parseInt(date2.getTime() / 1000);
// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;
// in Hours
var timeDifferenceInHours = timeDifference / 60 / 60;
// in weeks :)
var timeDifferenceInWeeks = timeDifferenceInHours / 24/7;
document.write(Math.ceil(timeDifferenceInWeeks));
</script>
You can use new Date() to get current date. please refer snippet.
<script>
// Here are the two dates to compare
var date1 = '2015-09-08';
var date2 = '2015-12-13';
// First we split the values to arrays date1[0] is the year, [1] the month and [2] the day
date1 = date1.split('-');
date2 = date2.split('-');
// Now we convert the array to a Date object, which has several helpful methods
date1 = new Date(date1[0], date1[1]-1, date1[2]);
date2 = new Date(date2[0], date2[1]-1, date2[2]);
// We use the getTime() method and get the unixtime (in milliseconds, but we want seconds, therefore we divide it through 1000)
date1_unixtime = parseInt(date1.getTime());
date2_unixtime = parseInt(date2.getTime());
date3_unixtime = parseInt((new Date()).getTime());
// This is the calculated difference in seconds
var timeDifference = date2_unixtime - date1_unixtime;
var timeDifferenceInWeeks1 = timeDifference / (1000*60*60*24*7);
var timeDifferenceInWeeks2 = (date3_unixtime - date2_unixtime) / (1000*60*60*24*7);
document.write(Math.ceil(timeDifferenceInWeeks1)+'--'+Math.ceil(timeDifferenceInWeeks2));
</script>
just use
var date2 = new Date();
now the date2 holds the current date and time from your machine.
I changed to a php code and the following is what I got to work.
<?
$strtDate = '2015-09-08';
$endDate = date('Y-m-d');
//$endDate = 'new Date();';
$startDateWeekCnt = round(floor( date('d',strtotime($strtDate)) / 7)) ;
// echo $startDateWeekCnt ."\n";
$endDateWeekCnt = round(ceil( date('d',strtotime($endDate)) / 7)) ;
//echo $endDateWeekCnt. "\n";
$datediff = strtotime(date('Y-m',strtotime($endDate))."-01") - strtotime(date('Y-m',strtotime($strtDate))."-01");
$totalnoOfWeek = round(floor($datediff/(60*60*24)) / 7) + $endDateWeekCnt - $startDateWeekCnt ;
echo $totalnoOfWeek ."\n";
?>

How do you get the unix timestamp for the start of today in javascript?

I realize that the current timestamp can be generated with the following...
var timestamp = Math.round((new Date()).getTime() / 1000);
What I'd like is the timestamp at the beginning of the current day. For example the current timestamp is roughly 1314297250, what I'd like to be able to generate is 1314230400 which is the beginning of today August 25th 2011.
Thanks for your help.
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay / 1000;
Well, the cleanest and fastest way to do this is with:
long timestamp = 1314297250;
long beginOfDay = timestamp - (timestamp % 86400);
where 86400 is the number of seconds in one day
var now = new Date; // now
now.setHours(0); // set hours to 0
now.setMinutes(0); // set minutes to 0
now.setSeconds(0); // set seconds to 0
var startOfDay = Math.floor(now / 1000); // divide by 1000, truncate milliseconds
var d = new Date();
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
var t = d / 1000;
Alternatively you could subtract the modulo of a days length in miliseconds e.g.
var day = 24*60*60*1000;
var start_of_today = Date.now() - Date.now() % day;
Luis Fontes' solution returns UTC time so it can be 1 hour (daylight saving time) different from setHours solution.
var d = new Date();
var t = d - (d % 86400000);
Simplified version of examples above (local time).
var d = new Date();
d.setHours(0,0,0,0);
var t = d / 1000;
Here you can find some performance tests: http://jsperf.com/calc-start-of-day
Another alternative for getting the beginning of the day is the following:
var now = new Date();
var beginningOfDay = new Date(now.getTime() -
now.getHours() * 60 * 60 * 1000 -
now.getMinutes() * 60 * 1000 -
now.getSeconds() * 1000 -
now.getMilliseconds());
var yoursystemday = new Date(new Date().getTime()-(120000*60+new Date().getTimezoneOffset()*60000));
yoursystemday = new Date();
var current_time_stamp = Math.round(yoursystemday.getTime()/1000);
For any date it's easy to get Timestamps of start/end of the date using ISO String of the date ('yyyy-mm-dd'):
var dateString = '2017-07-13';
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();
To get ISO String of today you would use (new Date()).toISOString().substring(0, 10)
So to get TS for today:
var dateString = (new Date()).toISOString().substring(0, 10);
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay.getTime() / 1000;

Categories