JavaScript compare two time strings - javascript

I have two string for time, one is current time and the other one is twenty minutes later. Here is the output:
10/1/2017 1:20:58 PM
10/1/2017 1:40:58 PM
Here is the code:
var now = new Date();
console.log(now.toLocaleDateString() + " " + now.toLocaleTimeString());
var in20 = new Date(now.getTime() + (1000*60*20));
console.log(in20.toLocaleDateString() + " " + in20.toLocaleTimeString());
Is there any way to check if the variable for twenty minutes later is before or after the current time variable as I not sure how to make time comparison based on two time strings. If it is after current time variable, return a true, otherwise return a false.
Any ideas? Thanks!

Best way to compare the 2 time string is convert them to milliseconds and then compare. For Eg.
var now = new Date();
console.log(now.toLocaleDateString() + " " + now.toLocaleTimeString());
var in20 = new Date(now.getTime() + (1000*60*20));
console.log(in20.toLocaleDateString() + " " + in20.toLocaleTimeString());
// at any instant suppose now is cuurent time then you can compare like
if(now.getTime() > in20.getTime()) {
console.log('current is greater')
} else {
console.log('in20 is greater')
}

Related

Inconsistent behaviour with Javascript Date getTime() function

I am trying to make a filter based on hours for timestamps (in this example filter for all times after 8 am):
var beginningTimeValue = new Date('2020-01-01 08:00:00');
var unique = [["value","value","value","value","12/01/2021 00:03:35","value"],["value","value","value","value","01/01/2020 00:03:35","value"], ["value","value","value","value","01/01/2020 08:03:35","value"], ["value","value","value","value","01/01/2020 13:03:35","value"]]
if(!beginningTimeValue == ""){
unique = unique.filter(function(row)
{
var rYear = row[4].substring(6, 10);
var rMonth = row[4].substring(3, 5);
var rDay = row[4].substring(0, 2);
var rHour = row[4].substring(11, 13);
var rMinute = row[4].substring(14, 16);
var rSecond = row[4].substring(17, 19);
var bTime = new Date(parseInt(rYear, 10), parseInt(rMonth, 10), parseInt(rDay, 10), parseInt(rHour, 10), parseInt(rMinute, 10), parseInt(rSecond, 10));
console.log("ODATE = " + rYear + "/" + rMonth + "/" + rDay + "_" + rHour + ":" + rMinute + ":" + rSecond);
console.log("BDATE = " + bTime.getFullYear() + "/" + bTime.getMonth() + "/" + bTime.getDate() + "_" + bTime.getHours() + ":" + bTime.getMinutes() + ":" + bTime.getSeconds());
beginningTimeValue.setYear(bTime.getYear());
beginningTimeValue.setMonth(bTime.getMonth());
beginningTimeValue.setDate(bTime.getDate());
if(bTime.getTime() >= beginningTimeValue.getTime()){
console.log(bTime.getTime()*24*3600*1000 + " VS " + beginningTimeValue.getTime()*24*3600*1000);
}
else{
console.log("FALSE");
}
return bTime.getTime() >= beginningTimeValue.getTime();
}
);
}
console.log(unique);
I have debugged my way to finding out that I wouldn't get a FALSE value in the 2nd IF, however I am at a loss as to why the .getTime() function returns vastly different values for my console log:
"136556220816000000000 VS -5.0438323821312e+21"
"136560264336000000000 VS -5.0438323821312e+21"
The problem is in the following line:
beginningTimeValue.setYear(bTime.getYear());
The (deprecated) getYear() function returns
[a] number representing the year of the given date, according to local
time, minus 1900.
The (also deprecated) setYear() function
[...] interprets any two-digit number as an offset to 1900
In your case, getYear() returns a value like 121, which is not a two-digit number. When you subsequently invoke setYear() with that value, you get a date that is set to the year 121 instead of 2021.
Since getTime() returns the number of milliseconds since 1970, and 121 is before 1970, you get a negative number.
TL;DR: use getFullYear() and setFullYear() instead of getYear() and setYear().

How can I compare time and dates accurately?

I want to check if the given time and date not passed yet so I have this:
var currentdate = new Date();
var currentTime = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
const givenTime = '2021-08-01T16:49:08.678Z';
// This is not comparing time , it only compares the dates
console.log(new Date(givenTime) > new Date, currentTime);
Unfortunately it seems that the code does not compare the times and it only compares the dates, so two times in the same day return a wrong result:
I mean code returns true if : const givenTime = '2021-08-01T16:49:08.678Z'; and current date is " 1/8/2021 # 18:7:21"
How can I compare time and dates accurately?
Convert those Date objects to timestamp(number) first and then compare equality of them.
example
var timestamp_1970 = new Date(0).getTime(); // 1970-01-01 00:00:00
var timestamp = new Date().getTime(); // Current Timestamp
It looks like you are trying to compare two local date/times. In that case, don't specify one of them as being UTC.
// delete the Z
const givenTime = '2021-08-01T16:49:08.678';
Note that this snippet will only return "false" if it's currently later than 4:49 pm in your local time zone. For me, it's not, so I get "true".
Also, new Date(givenTime) > new Date won't work. I believe you mean new Date(givenTime) > new Date(currentdate) or new Date(givenTime) > new Date() - they are essentially the same.
var currentdate = new Date();
var currentTime = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
const givenTime = '2021-08-01T16:49:08.678';
// This is not comparing time , it only compares the dates
console.log(new Date(givenTime) > new Date(currentdate), currentTime);
I just used this and it works perfectly without touching the givenTime:
var currentTime = new Date().toISOString();
console.log(currentTime)
const givenTime = '2021-08-01T14:13:08.678Z';
console.log(givenTime > currentTime);
The easiest way to compare two dates is by using UNIX timestamps.
Adding .getTime() after const currentDate converts the date object into a UNIX timestamp. UNIX timestamps are easily comparable. const givenTime = new Date('2021-08-01T16:49:08.678Z').getTime(); also returns a UNIX timestamp, which you can then compare with the current time.

Check if time difference is less than 45 mins and run function - AngularJS

This is an easy thing to do in PHP with code like this;
if (strtotime($given_time) >= time()+300) echo "You are online";
But can't find anything on SO to do exactly this in javascript.
I want to check if the difference between a given time and the current time is less than 45mins
For instance
$scope.given_time = "14:10:00"
$scope.current_time = new Date();
I'm only concerned with the time part. I need to extract time part from new Date(); and then compare.
Then this should be true
How can I achieve this with Javascript:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Javascript uses unix timestamps in milliseconds, so it is similar to the output of strtotime (which uses seconds).
var date = new Date();
Then you'll need to do the calculation from milliseconds. (Minutes * 60 * 1000)
You can also use date.parse() to parse a string to milliseconds, just like strtotime() in PHP does to seconds.
In full:
var date = new Date();
var last = new Date('Previous Date'); // or a previous millisecond timestamp
if ( ( date - last ) > ( 45 * 60 * 1000 ) ) {
// do something
}
You could use a static date to compare just time, this is exactly what strtotime does if you exclude the date:
var last = new Date('1/1/70 14:10:00');
var date = new Date('1/1/70 14:30:00');
However, this approach will fail if you're trying to compare time that cross over day boundaries.
Try this:
function checkTime(time) {
var date = new Date();
var date1 = new Date((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time);
var minutes = (date1.getTime() - date.getTime()) / (60 * 1000);
if (minutes > 45 || (minutes < 0 && minutes > -1395)) {
// greater than 45 is todays time is above 45 minutes
// less than 0 means the next available time will be tomorrow and the greater than -1395 means it will be more than 45 minutes from now into tomorrow
document.write(time + ': true<br />');
} else {
document.write(time + ': false<br />');
}
}
checkTime("14:10:00");
checkTime("16:30:00");
checkTime("17:10:00");
There's a JavaScript method called getMinutes(); you can use to get only the minutes and compare.
Your code should look something like:
var received_time = "14:10:00".split(':');
var minute = '';
if(received_time.length === 3) {
minute = parseInt(received_time[1], 10);
}
$scope.given_time = minute;
var the_time = new Date();
$scope.current_time = the_time.getMinutes();
And you now can do your thing:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Using a library like moment.js you can simply diff the two times.
var $log = $("#log");
/* Difference between just times */
$log.append("Difference between times\n");
var givenTime = moment("14:10:00", "HH:mm:ss");
var minutesPassed = moment("14:30:00", "HH:mm:ss").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
/* Better: Difference between times that have dates attached to them and cross a day boundary. */
$log.append("\n\nDifference between dates with times\n");
givenTime = moment("2015-12-03 23:33:00");
minutesPassed = moment("2015-12-04 00:14:00").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://momentjs.com/downloads/moment.js"></script>
<p>Results:</p>
<hr>
<pre id="log"></pre>
<hr>
Caveat: If the given time is yesterday such as 11:30pm and the current time is 12:10am then you will get the wrong result. You'd want to use a date with the time if this type of thing is an issue for your use case.
The moment.js documentation
http://momentjs.com/docs/
Angular directive for moment documentation
https://github.com/urish/angular-moment/blob/master/README.md

trying to encage getDate() inside a var

Someone could please help me understand why on Earth this is not working?
document.write('messing with the dates: <br>')
var nowDate = new Date();
var currentDay = nowDate.getDate();
nowDate.setDate(currentDay + 1);
document.write('if it\'s not inside a variable, it\'s nice and tidy: ' + nowDate.getDate() + '<br>');
var tomorrow = (nowDate.setDate(currentDay + 1));
document.write('but as soon as I put it inside a var, it becomes terrible: ' + tomorrow);
document.write('and this is not even working' + tomorrow.getDate());
setDate does two things, changes the Date Object itselfs, and returns the number of milliseconds since 1 January 1970 00:00:00 UTC of the resulting date.
Which is the number you're getting on tomorrow
I guess you should use it like that to achive what you're trying to do:
var tomorrow = new Date((nowDate.setDate(currentDay + 1)))

Adding Day to Date to Make Current Date Tomorrow - Javascript [duplicate]

This question already has answers here:
How to add days to Date?
(56 answers)
Closed 8 years ago.
Hi Everyone and thanks in advance for the help. I'm having an issue with getting my Javascript date code to advance from the current date to tomorrow's date. I've searched here in previous posts but the answers don't seem to be working.
<SCRIPT LANGUAGE="JavaScript">
// Get today's current date.
var now = new Date();
// Array list of days.
var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
// Array list of months.
var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
// Calculate the number of the current day in the week.
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
// Calculate four digit year.
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;
}
// Join it all together
today = days[now.getDay()] + ", " +
months[now.getMonth()] + " " +
date + ", " +
(fourdigits(now.getYear())) ;
</script>
Where would the + 1 be inserted in order to make the date tomorrow's date?
now.setDate(now.getDate() + daysToAdd);
should do the trick. It's not even jQuery, just Javascript. If you're getting the 1 added to the end of the string make sure now is still being treated as a Date and hasn't been reassigned somewhere to a different type.
It shouldn't matter whether daysToAdd is a literal or a variable, either. Both should work.
More specifically, this should work:
<SCRIPT LANGUAGE="JavaScript">
// Get today's current date.
var now = new Date();
now.setDate(now.getDate() + 1);
// Array list of days.
var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
// Array list of months.
var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
// Calculate the number of the current day in the week.
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
// Calculate four digit year.
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;
}
// Join it all together
today = days[now.getDay()] + ", " +
months[now.getMonth()] + " " +
date + ", " +
(fourdigits(now.getYear())) ;
</script>

Categories

Resources