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;
}
Related
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
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.
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>
I have 2 times for example: 10:00 and 1:00 now i want to check if current time... is between these 2 times in javascript.
The problem is that the closing time in this case is a next day so its before the openingstime. How can i do this the proper way for some reason i can not get around this.
i hav efound that this could solve it:
var start = new Date(2012,6,20,13).getTime();
var now = new Date().getTime();
var end = new Date(2012,6,21,2).getTime();
if( (start < now ) && (now < end )) {
console.log("opened");
}
else {
console.log("closed");
}
but how can i do it with 2 string formats like 10:00 and 2:00 because i do not see a option to put a time alone
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
You could use a simple function like this to convert your time to a number of minutes since 0:00:
function getMinutes(str) {
var time = str.split(':');
return time[0]*60+time[1]*1;
}
And a similar function to get the current time into the same form in order to compare:
function getMinutesNow() {
var timeNow = new Date();
return timeNow.getHours()*60+timeNow.getMinutes();
}
Then convert both opening and closing time and, if it happens that closing time is before opening time, add 24 hours to it.
var now = getMinutesNow();
var start = getMinutes('10:00');
var end = getMinutes('2:00');
if (start > end) end += getMinutes('24:00');
if ((now > start) && (now < end)) { // your code here
This is the solution I've gotten to after a bit of fiddling. At the current time of 3:24 am, it outputs the correct information. changing the now array to be [13,00] also gave the correct result of 'closed' Give it a test run through to make sure it works correctly.
Edit
jQuery included solely because I am brain dead.
Edit#2
I noticed now (9pm my time) that my conversion wasn't working, it was saying 'closed', when it shouldn't have. So far, this works for any and all numbers I've put in it to test.
var start_time = [20,00]
var end_time = [12,00]
//We've got the two start times as an array of hours/minutes values.
var dateObj = new Date(); //I just feel dirty making multiple calls to new Date().etc
var now = [dateObj.getHours(),dateObj.getMinutes()]; //Gets the current Hours/Minutes
if(end_time[0] < start_time[0] && now[0] < start_time[0]){
start_time[0] -= 24; //This is something I came up with because I do a lot of math.
}else if(start_time[0] > end_time[0]){
end_time[0]+=24;
}
var el=$('#result');
var start_string = to_hms_string(start_time); //the start string converted to a string format. Made comparisons easier.
var end_string = to_hms_string(end_time); //See Above
var now_string = to_hms_string(now); //Above
console.log(start_string, now_string, end_string);
var status = (start_string < now_string && now_string < end_string) ? "Open" : "Closed";
el.html(status);
//Function to_hms_string stands for "hour-minute-second" string. First name that came up.
function to_hms_string(timearr){
var minutes = 60+timearr[1];
var hours = "";
if(Math.abs(timearr[0]) < 10){
hours = "0";
}
hours = (timearr[0]<0) ? "-"+hours+Math.abs(timearr[0]) : hours+timearr[0];
return hours+":"+minutes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
PlaceHolder
</div>
You can do this, get current time. Then define you start time and end time based on the current time getting the year, month, date for tomorrow's date add 1 to the start's date see code below. Then you can compare the time the same fi condition you have. Good luck
var now = new Date();
var start = new Date(now.getFullYear(),now.getMonth(),now.getDate(),7).getTime();
var end = new Date(now.getFullYear(),now.getMonth(),now.getDate() + 1,2).getTime();
now = now.getTime();
if( now >= start && now < end) {
console.log("opened");
}
else {
console.log("closed");
}
***EDIT**
You can convert the current time to millis after you get the year, month and date. Then use your current if condition.
Jhecht This thing right here:
if(end_time[0] < start_time[0] && now[0] < start_time[0]){
start_time[0] -= 24;
}else if(start_time[0] > end_time[0]){
end_time[0]+=24;
}
it's brilliant. It works and this is the correct answer. Great job!
I followed this tutorial, but I wanted to just be able to set a date and have it countdown to that date.
Even so, it would just base it off my computer's time; how can I make it so it's standard for everyone?
He mentioned setUTCDate() but I have no idea how to implement it?
Here's some code to get you started. It gets the UTC time and alert's it, formatted:
// By default, JS does not pad times with zeros
function checkTime(i) {
if(i<10) i='0'+i;
return i;
}
// Set current UTC time
var d = new Date();
var now = checkTime(d.getUTCHours()) + ':' +
checkTime(d.getUTCMinutes()) + ':' +
checkTime(d.getUTCSeconds());
// Output
alert(now);
Here's a JSFiddle.
Remember: UTC != GMT (read on if you want this to always match the UK time).
BST (when the clocks go forward) will need to be factored in for anyone in the UK wanting to use this solution.
Here's a function I wrote earlier:
// Function returning 0 or 1 depending on whether BST is in effect
function isBSTinEffect()
{
var d = new Date();
// Loop over the 31 days of March for the current year
for(var i=31; i>0; i--)
{
var tmp = new Date(d.getFullYear(), 2, i);
if(tmp.getDay() == 0) { lSoM = tmp; break; }
}
// Loop over the 31 days of October for the current year
for(var i=31; i>0; i--)
{
var tmp = new Date(d.getFullYear(), 9, i);
if(tmp.getDay() == 0) { lSoO = tmp; break; }
}
if(d < lSoM || d > lSoO) return 0;
else return 1;
}
To factor in BST, put that function before // Set current UTC time and change checkTime(d.getUTCHours()) to checkTime(d.getUTCHours()+isBSTinEffect())