Increase time by an hour before comparing - javascript

I have code containing time in the military format.
<div class="em" data-time="17:30">
I am comparing that time to the current time to determine if the set time has passed or not.
var curDate = new Date(),
curTime = curDate.getTime(),
givenTm = $(this).find('.em').attr('data-time'),
givenMs = Date.parse(curDate.toDateString() + ' ' + givenTm);
if (curTime > givenMs) {
// time has passed
}
I need to modify my code to check not against the time in data attribute, but an hour after that given time. Also my given time can only be on the same day and no later then 23:30, which means I only care if the given time is no later then 23:00.
How do I put all this together?

To adjust by an hour, just add one hour in milliseconds (60 * 60 * 1000) to the comparison. To ignore any given time after 2300, you'll need to add another clause into the conditional. So something like this might do it:
if (new Date(givenMs).getHours() < 23
&& curTime > givenMs + 3600000) {
// time has passed
}
Hopefully that helps.

Try using .toJSON , String.prototype.replace() , String.prototype.slice()
$("div").click(function() {
var curDate = new Date(),
curTime = curDate.toJSON(),
givenTm = $(this).find(".em").attr("data-time")
.replace(/(\d+)(?=:)/, function(match) {
return Number(match) + 1
}),
curr = curTime.slice(11, -8).replace(":", ""),
given = givenTm.replace(":", "");
if (curr < 2330 && given < 2330) {
// time has passed
console.log("currTime:", curr, "givenTime:", given,
"time has not passed")
} else {
console.log("time has passed")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div>click
<div class="em" data-time="17:30">
</div>

Related

How to compare two times in javascript

I'm struggling to compare two times.
I need to print Current class going based on the current time.
Example: current time based class going on the college/school
var now = new Date();
var TwentyFourHour = now.getHours();
var hour = now.getHours();
var min = now.getMinutes();
var mid = 'PM';
if (min < 10) {
min = "0" + min;
}
if (hour > 12) {
hour = hour - 12;
}
if (hour == 0) {
hour = 12;
}
if (TwentyFourHour < 12) {
mid = 'AM';
}
Current_time = hour + ':' + min + ':' + mid;
start_time = "09:00:PM";
end_time = "10:00:PM";
if (parseInt(start_time) <= parseInt(Current_time) || parseInt(end_time) >= parseInt(Current_time)) {
console.log("C programming class is going");
} else {
console.log("No class are avalible");
}
OUTPUT:
C programming class is going....
It seems you are looking for the shortest path to have your homework done.
Please check the references for Date function:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
Some tips:
Make sure you understand how the Date object is created. You can use strings!
If you want to define date manually using each day, month , value, you can!
Check your strings.. are you sure "09:00:PM" is a valid string for date?
Are you sure you can use parseInt for parsing dates?
Anyway, you need to do more research.
The easiest way to check if a time is between a start and an end time is to store the time using unix time(https://en.wikipedia.org/wiki/Unix_time). It represents the time in seconds after 00:00:00 UTC on 1 January 1970. so you can do the following:
const startTime = 1624802400 // 27.6.21 16:00
const endTime = 1624809600 //27.6.21 18:00
const currentTime = Date.now()/1000
if(currentTime < endTime && currentTime > startTime){
console.log('Class is going')
}
if(currentTime > endTime){
console.log('Class ended')
}
if(currentTime < startTime){
console.log('Class has not started')
}
Date.now() returns the current time in milliseconds so you need to divide it by 1000

Check if the current time falls in this range?

I have a below "start":"23:00" and "end":"24:00".
I want to check whether the current time falls in between them.
I have the below code, which works fine for Eastern time zone, but does not work in other time zones.
isBetween(start, end) {
var d = new Date();
var time = (d.getHours()) + ":" (d.getMinutes());
return time >= start && time <= end;
}
How do i convert my start and end to local timezone and then do the comparison? I am getting the time in EDT from server.
Try the following:-
function isBetweenHours(startHour, endHour)
{
var now = new Date().getHours();
return now >= parseInt(startHour, 10) && now <= parseInt(endHour, 10);
}
//Then you would use it like this:
if( isBetweenHours('23:00', '24:00') ) {
console.log('It is in between!!');
} else {
console.log('It is not in the range!');
}
Instead of converting your start and end to the local timezone, I suggest to do the other way round :) Adjust the local time to UTC time and compare with that. Keep your start and end accordingly as well. Something like this:
isBetween(start, end) {
var d = new Date();
d.setMinutes(d.getTimezoneOffset());
var time = (d.getHours()) + ":" (d.getMinutes());
return time >= start && time <= end;
}

Check if time is falling under specific timeframe

I have a variable that stores a time value.
var cabtime = ["09:30:00"];
Variable time value is in 24-hour clock. That means 02:30:0PM will come as 14:30:00.
I want to check if the variable time falls under 08:00AM to 10:00AM window. If yes then I'll do an action.
Any pointers in this regard?
You could parse the time into seconds since midnight using:
var cabtime = ["HH:MM:SS"] // in 24hr time
function parseTime (string) {
parts = string.split(':').map(x => parseInt(x))
seconds = parts[0] * 3600 + parts[1] * 60 + parts[0]
return seconds
}
Then you can parse the time and the upper/lower bounds, and test using:
time = parseTime(cabtime[0])
lower = parseTime('08:00:00')
upper = parseTime('10:00:00')
if (time >= lower && time <= upper) {
print('Inside the range')
}
You can solve it easily by converting your strings to Date objects and compare them than.
var cabtime = ["09:30"];
function checkTimeRange(time, from, to, reldate) {
if (undefined === reldate) {
reldate = '0000T'; // the date the time strings are related to
}
let dtime = new Date(reldate + time);
let dfrom = new Date(reldate + from);
let dto = new Date(reldate + to);
return dfrom <= dtime && dtime <= dto;
}
checkTimeRange(cabtime[0], '08:00', '10:00'); // returns true
If you have full dates (e.g. '2019-07-25T09:30:00') instead of just the clock time you should provide for the parameter `reldate' an empty string.
* update: changed the wrong date format to standard format
* update: changed the date format again to be more fancy

How to convert user timezone to UTC?

I'm using the TimeIt code on my site, it can be found here: http://codegen.in/timeit/
This is the direct link to the code: https://res.cloudinary.com/vsevolodts/raw/upload/v1503371762/timeit.min.js
It looks like this:
//version 3. 2017-08-13
function timeit() {
var next_run_array = []; //array of dates/time on a page used to rerun function if a change should happen during the session
var curDate = new Date();
Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1;
var dd = this.getDate();
return [this.getFullYear(),
(mm > 9 ? '' : '0') + mm,
(dd > 9 ? '' : '0') + dd
].join('-');
};
var curDateYMD = curDate.yyyymmdd();
$('.timeit').each(function() {
var end = $(this).data('end'),
start = $(this).data('start');
//check if date or time value has valid format and push it to the list of refresh anchors
var startDate = checkdate(start, this);
var endDate = checkdate(end, this);
nextrun(startDate);
nextrun(endDate);
//add a datetime when the page needs to be refreshed (now+24 hrs time span only)
function nextrun(date) {
var nextruntimeout = date - curDate;
if (nextruntimeout < 1000 * 60 * 60 * 24 && nextruntimeout > 1000) {
next_run_array.push(nextruntimeout);
}
}
// Main Function
//check if the evend outside of a desired time span
if (((startDate < endDate) && (startDate > curDate || endDate < curDate)) ||
((startDate > endDate) && (startDate >= curDate) && (endDate <= curDate))
) {
$(this).addClass('hidden');
} else {
$(this).removeClass('hidden');
}
//Support Functions
//correct data creation from a string. accepted format YYYY-MM-DD HH:MM
function parseISO8601(d) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)?.(\d\d)?.(\d\d)\s*$/,
date = new Date(NaN),
datenew,
month,
dateString=d.substr(0, d.indexOf(' '));
parts = isoExp.exec(d);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
date = new Date(parts[1], month - 1, parts[3], parts[4], parts[5])
}
return date;
}
//unification of the date string to the format YYYY-MM-DD HH:MM
function checkdate(date, obj) {
if (date) {
//check if only time is set (HH:MM); if so, add today's date
if (String(date).length < 6 && String(date).indexOf(":") > -1) {
date = curDateYMD + ' ' + String(date);
}
//check if only date is set; if so add 00:00 to the end of date
if (String(date).indexOf(":") == -1) {
date = date + ' 00:00';
}
//check if date is valid (avoid valid time)
var res = date.split(":"),
h = String(res.slice(0, 1)),
hours = h.substr(h.length - 2),
minutes = res.slice(1);
var timetest = (hours < 24 && minutes < 60) ? true : false;
//check if date is could be created from a value; if fails try to parse a string to a format
var returndate = new Date(date);
if (returndate == 'Invalid Date') {
var returndate = parseISO8601(date);
};
if (returndate == 'Invalid Date' || !timetest) {
//highlight the element if the is an error. use own \.error class if needed
$(obj).addClass("error").attr('title', '"' + date + '" date is incorrect; please use YYYY-MM-DD HH:MM format');
}
return returndate.getTime();
} else {
//if datetime is not set, just return current date-time
return curDate.getTime();
}
}
});
/* Schedule next runs */
if (next_run_array.length > 0) {
var nextruntime = Math.min.apply(null, next_run_array);
console.log("next run of timeit function is in " + nextruntime / 1000 + "seconds");
setTimeout(function() {
timeit();
}, nextruntime);
}
}
timeit();
(
Then you just put the embed code:
<div class="timeit" data-start="2019-02-15" data-end="2019-07-25 23:59">
This content will be shown between 2019-02-15 - 2019-07-25
</div>...<script src="/js/timeit.js"></script>
The idea is: my content is being shown between a certain period of time. I would like it to work with the UTC time zone, but right now the code is getting the date/hour info from the user's local time zone. So my content becomes available for example not at 8 AM UTC, but at 8 AM of the user's local time zone. I would like to change that.
I really, really tried to work this out on my own, but I guess this is beyond my skill set (which is pretty low). I'm confused by all the info about those ISO 8601, new Date, Date, I can't really find where it says "get the time from this source" to replace it with "get it from UTC". So - if any of you would just take a look at it and tell me what to put where, I would be extremely grateful.
Thank you all for your time!
Since you can't use server-side scripting because of Weebly... You will have to rely on the client's clock which can be tweeked. And the hidden class can easily be removed... But it seems you don't have the choice.
Now, I will suggest you to forget about the TimeIT plugin.
When it comes to dates in JavaScript/jQuery, I always recommand the use of moment.js which is really easy to use (you won't have to perform complex caluculations anymore) and fully documented, so you can do whatever you wish.
Here, content hiding based on start/end dates in data attributes would look like this:
$(document).ready(function(){
var utc_date = moment().utc().format("YYYY-MM-DD HH:mm"); // Client's date/time in UTC
$(".timeit").each(function(){
var start = moment($(this).data("start")).format("YYYY-MM-DD HH:mm");
var end = moment($(this).data("end")).format("YYYY-MM-DD HH:mm");
console.log((utc_date>start && utc_date<end)?"Content displayed":"Content hidden");
$(this).addClass("hidden"); // Hide content by default
if(utc_date>start && utc_date<end){
$(this).removeClass("hidden"); // Show content if now is between start/end dates
}
});
}); // ready
.hidden{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<div class="timeit" data-start="2019-02-15" data-end="2019-07-25 23:59">
This content will be shown between the dates in data attributes
</div>
You can try it in CodePen... Change the start date and hit "Run". I left some console logs so you can understand what is going on.
For more, explore moment.js documentation.

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

Categories

Resources