Javascript has built-in function for time where
var date = new Date();
d.getHours() //gets the hour in integer 0-23
d.getMinutes() //gets the minute in integer 0-59
I would like function (e.g. A()) to run between 0:35 and 4:35
Is this possible to do using just simple logic operation (&&, ||)?
I don't think it is possible, but I wanted to know the elegant way to implement it.
You could use the timestamp to compare.
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var start = new Date(year, month, day, 0, 35);
var end = new Date(year, month, day, 4, 35);
if (date.getTime() >= start.getTime() && date.getTime() <= end.getTime()) {
//...
}
var date = Date.now(); // ES5 - or new Date().getTime()
var sec = (date / 1000); // seconds since epoch
sec = sec % 86400; // seconds since midnight
var mins = sec / 60; // minutes since midnight
if (mins >= 35 && mins < 4*60+35) {
A();
}
Technically it's possible, but you are absolutely right in that this is not an elegant solution:
var h = d.getHours();
var m = d.getMinutes();
if ((h == 0 && m >= 35) || (h > 0 && h < 4) || (h == 4 && m <=35)) {
A();
}
This should work:
function foo(){
var now = new Date();
if( (now.getHours() < 1 && now.getMinutes() < 35)
|| (now.getHours() > 3 && now.getMinutes() > 35) ){
return false; //if it isn't in your time, return false
}
//put your code here. this will run between the hours of 12:35AM and 4:35AM local time
}
I hope this is what you are looking for. If not, let me know.
Related
I'm trying to write a statement that says "if time is this and less than that then". I can use get hours and get min. However, I'm having problems combining a time such as 9:30.
Example,
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var mintues = now.getMinutes();
if (day == 0 && hour >= 9 && hour <= 11 && mintues >= 30) {
document.write(now);
}
This only if the time is less between 9:30 10. As soon as the clock hits 10 the minutes are then < 30 and the script breaks.
Any thoughts on how to better incorporate the time function to make this theory work?
Thanks,
use new Date().getTime() returns milliseconds for much easier comparison. This way there is no need to check hour, min, second, millisecond. Fiddle link
var d930 = new Date(2010, 12, 21, 9, 30, 0, 0), // today 9:30:00:000
d931 = new Date(2010, 12, 21, 9, 31, 0, 0), // today 9:31:00:000
t930 = d930.getTime(),
t931 = d931.getTime();
console.log(t931 > t930);
This way your code can check against a static 9:30 time.
var time930 = new Date(2010, 12, 21, 9, 30, 0, 0).getTime(),
sunday = 0,
now = new Date();
if(now.getDay() == sunday && now.getTime() >= time930){
/* do stuff */
}
You have a few typos and basic javascript errors.
Might wanna brush up on the basics.
W3Schools is where I learned all I know.
It works fine if you fix them...
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var minutes = now.getMinutes();
if(day == 0 && hour == 9 && minutes < 30 && minutes > 10 || day == 0 && hour == 9)
document.write('Time is between 9:10 and 9:30');
Think of the if statement as basic logic.
If the day is Sunday(0)
AND the hour is 9
AND the minutes are greater than 10
AND the minutes are less than 10
OR the day is Sunday(0)
AND the hour is before 9.
var now = new Date();
var closeTime = new Date();
closeTime.setHours(9); closeTime.setMinutes(30);
console.log(now, closeTime, now.getTime() >= closeTime.getTime());
close time is based on today, then we just change the hours and minutes to 9:30.
I made this solution simple and easy to read (thus easy to adjust).
// we need a function that makes hours and minutes a two digit number
Object.prototype.twoDigits = function () {
return ("0" + this).slice(-2);
}
// get current date and time
let now = new Date();
// compile the current hour and minutes in the format 09:35
timeOfDay = now.getHours().twoDigits() + ':' + now.getMinutes().twoDigits();
// test if timeOfDay is within a given time frame
if ('09:30' <= timeOfDay && timeOfDay <= '11:30') {
console.log('inside time frame');
} else {
console.log('outside time frame');
}
I had a similar problem to solve today, I setup a little component that returns if a place of business is open or not. Got the time by dividing the minutes by 100 then adding it to the hours. So 8:30 is represented as 8.3
let d = new Date()
let day = d.getDay()
let hours = d.getHours()
let minutes = d.getMinutes() / 100
let time = hours + minutes
if (day == 1) {
if (time > 8.3 && time < 17.3) {
setIsOpen(true)
} else {
setIsOpen(false)
}
}
if the hour is less than 9, true
or
if hour is 9 and minutes lt 30, true
so that would look like
if ((hour < 9) || (hour == 9 && minutes < 30))
Use words to figure out your logic. Symbols are just shortcuts.
One way is to do a direct comparison on date objects. Choose an arbitrary year, month and day, and then incorporate your times as follows:
var older = new Date("1980-01-01 12:15");
var newer = new Date("1980-01-01 12:30");
if (newer > older){
alert("Newer time is newer");
} else {
alert ("The time is not newer");
}
The MDC documentation on the Date object will help with some more details. The bottom line is that if you want to compare times, you don't actually need to call any methods on the objects, and it's possible to directly compare them. The date() object can take a variety of strings to assign a new time to the returned instance, these are from the MDC documentation:
today = new Date();
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
As you can see, it's pretty simple. Don't complicate, and have a look through the documentation :)
While we're here, here's a test using your example:
var base = new Date("1980-01-01 9:30");
var test = new Date("1980-01-01 9:30:01");
if (test >= base){
alert("test time is newer or equal to base time");
} else {
alert ("test time is older than 9.30");
}
Try this:
var now = new Date();
var hour = now.getHours();
var mintues = now.getMinutes();
if(
(hour*60 + mintues) > 570 &&
hour <= 11
)
{
document.write(now);
}
I don't quite fully understand your question but hope this helps.
c = new Date();
nhour = c.getHours();
nmin = c.getMinutes();
if(nmin <= 9) {
nmin = "0" + nmin;
}
if(nhour <= 9) {
nhour = "0" + nhour;
}
newtime = nhour + "" + nmin;
if(newtime <= 0930){
alert("It is before 9:30am or earlier");
}
Ok so what the title says. I am doing this on a server, so I get the server's time using some PHP code. The problem is that it is a time frame without exact round hour values. Should I use nested if else statements?
var serverTimestampMillis = <?php print time() * 1000 ?>;
var checkInterval = 1000;
var checkTime = function () {
serverTimestampMillis += checkInterval;
var now = new Date(serverTimestampMillis);
var timeDiv = document.getElementById('timeDiv');
var messageDiv = document.getElementById('messageDiv');
timeDiv.innerHTML = now.toString();
var dayOfWeek = now.getDay(); // 0 = Sunday, 1 = Monday, ... 6 = Saturday
var hour = now.getHours(); // 0 = 12am, 1 = 1am, ... 18 = 6pm
var minutes = now.getMinutes();
// check if it's Monday to Thursday between 8:30am and 6:30pm
// this is where I don't know how to check 8:30
if (dayOfWeek > 0 && dayOfWeek < 5 && hour > 8 && hour < 18) {
messageDiv.innerHTML = 'Yes, we are open!';
messageDiv.className='open';
}
else {
messageDiv.innerHTML = 'Sorry, we\'re closed!';
messageDiv.className='closed';
}
};
// check the time every 1000 milliseconds
setInterval(checkTime, checkInterval);
checkTime();
thank you in advance, and sorry for being a noob
Compare between two dates using a helper function:
function createDateTime(time) {
var splitted = time.split(':');
if (splitted.length != 2) return undefined;
var date = new Date();
date.setHours(parseInt(splitted[0], 10));
date.setMinutes(parseInt(splitted[1], 10));
date.setSeconds(0);
return date;
}
var startDate = createDateTime("8:30");
var endDate = createDateTime("17:30");
var now = new Date();
var isBetween = startDate <= now && now <= endDate;
console.log(isBetween);
JSFIDDLE.
You can just nest your statements, like you said (to make it easier to read), and then check the specific edge cases (8:30-9 and 18:00-18:30).
if (dayOfWeek > 0 && dayOfWeek < 5) {
if ((hour > 8 && hour < 18) ||
(hour == 8 && minutes >= 30) ||
(hour == 18 && minutes <= 30)) {
messageDiv.innerHTML = 'Yes, we are open!';
messageDiv.className='open';
}
}
I have two variables called 'startTime' and 'endTime'.
I need to know whether current time falls between startTime and EndTime. How would I do this using JavaScript only?
var startTime = '15:10:10';
var endTime = '22:30:00';
var currentDateTime = new Date();
//is current Time between startTime and endTime ???
UPDATE 1:
I was able to get this using following code. You can check out the code at: https://jsfiddle.net/sun21170/d3sdxwpb/1/
var dt = new Date();//current Date that gives us current Time also
var startTime = '03:30:20';
var endTime = '23:50:10';
var s = startTime.split(':');
var dt1 = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate(),
parseInt(s[0]), parseInt(s[1]), parseInt(s[2]));
var e = endTime.split(':');
var dt2 = new Date(dt.getFullYear(), dt.getMonth(),
dt.getDate(),parseInt(e[0]), parseInt(e[1]), parseInt(e[2]));
alert( (dt >= dt1 && dt <= dt2) ? 'Current time is between startTime and endTime' :
'Current time is NOT between startTime and endTime');
alert ('dt = ' + dt + ', dt1 = ' + dt1 + ', dt2 =' + dt2)
var startTime = '15:10:10';
var endTime = '22:30:00';
currentDate = new Date()
startDate = new Date(currentDate.getTime());
startDate.setHours(startTime.split(":")[0]);
startDate.setMinutes(startTime.split(":")[1]);
startDate.setSeconds(startTime.split(":")[2]);
endDate = new Date(currentDate.getTime());
endDate.setHours(endTime.split(":")[0]);
endDate.setMinutes(endTime.split(":")[1]);
endDate.setSeconds(endTime.split(":")[2]);
valid = startDate < currentDate && endDate > currentDate
You can possibly do something like this if you can rely on your strings being in the correct format:
var setDateTime = function(date, str){
var sp = str.split(':');
date.setHours(parseInt(sp[0],10));
date.setMinutes(parseInt(sp[1],10));
date.setSeconds(parseInt(sp[2],10));
return date;
}
var current = new Date();
var c = current.getTime()
, start = setDateTime(new Date(current), '15:10:10')
, end = setDateTime(new Date(current), '22:30:00');
return (
c > start.getTime() &&
c < end.getTime());
I wanted to compare a time range in the day ... so I wrote this simple logic where the time is converted into minutes and then compared.
const marketOpen = 9 * 60 + 15 // minutes
const marketClosed = 15 * 60 + 30 // minutes
var now = new Date();
var currentTime = now.getHours() * 60 + now.getMinutes(); // Minutes since Midnight
if(currentTime > marketOpen && currentTime < marketClosed){ }
Note that I have not taken UTC minutes and hours since I want to use the local time, In my case it was IST time.
A different approach:
First, convert your currentDate
var totalSec = new Date().getTime() / 1000;
var hours = parseInt( totalSec / 3600 ) % 24;
var minutes = parseInt( totalSec / 60 ) % 60;
var seconds = totalSec % 60;
var numberToCompare = hours*10000+minutes*100+seconds;
cf Convert seconds to HH-MM-SS with JavaScript?
Then compare:
(numberToCompare < (endTime.split(':')[0]*10000+endTime.split(':')[1]*100+endTime.split(':')[2]*1)
or
(numberToCompare > (endTime.split(':')[0]*10000+endTime.split(':')[1]*100+endTime.split(':')[2]*1)
Just another way I have for matching periods in a day, precision is in minutes, but adding seconds is trivial.
function isValid(date, h1, m1, h2, m2) {
var h = date.getHours();
var m = date.getMinutes();
return (h1 < h || h1 == h && m1 <= m) && (h < h2 || h == h2 && m <= m2);
}
isValid(new Date(), 15, 10, 22, 30);
I am looking to show an estimated delivery date on the product page for each delivery option we have. I have read through the code in Shopify Variants by Steph Sharp which would work brilliantly except we would need it to be fixed to the current day up until 3pm and then switch to the next working day after 3pm. (Basically taking away the option for the customer to choose the dispatch day.)
I can’t quite get it to work by butchering this code into our template. This is what I have butchered together which seems to work okay but rather than have MON, TUE, WED, … I want to set them as the future dates. Any advice?
EDIT: Also I heard Palec is after using a timer code with this code too. So I will add that in.
<script language="JavaScript">
function day(a) {
var date = new Date();
var days = ["Mon","Tue","Wed","Thur","Fri","Mon","Tue","Wed","Thur","Fri","Mon","Tue","Wed","Thur","Fri"];
var today = date.getDay();
if (today == 1) today = 0; //Monday
if (today == 2) today = 1; //Tuesday
if (today == 3) today = 2; //Wednesday
if (today == 4) today = 4; //Thursday
if (today == 5) today = 5; //Friday
if (today == 6) today = -1; //Saturday Moved To Monday
if (today == 0) today = -1; //Sunday Moved To Monday
h = date.getHours();
if (h <= 9) h = "0" + h;
time = h;
if (time > 15) today++;
var expected = today + a;
var main = days[expected];
document.write('STANDARD DELIVERY ESTIMATE: ');
document.write(main);
}
</script>
<body>
<script language="JavaScript">
day(1)
</script>
I would try something like this:
function day(a) {
var date = new Date();
var hours = date.getHours();
// If after 3pm, add 1 day
if(hours > 15) a++;
var expectedDeliveryDate = addWeekdays(date, a);
document.write(expectedDeliveryDate.toDateString() + ' with Standard Delivery');
}
function addWeekdays(fromDate, days) {
var count = 0;
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate;
}
(The code in the addWeekdays function is from this answer on Stack Overflow.)
This code just displays the day name (like the code in your question), but you can format expectedDeliveryDate however you want.
EDIT: I updated my code to use expectedDeliveryDate.toDateString() as specified in the comments. Note that you no longer need the days array or expectedDeliveryDay variable. (You've still got them in your answer but they're not being used.)
This is my final code, based on Steph Sharp’s answer.
function day(a) {
var date = new Date();
var hours = date.getHours();
// If after 3pm, add 1 day
if (hours >= 15) a++;
var expectedDeliveryDate = addWeekdays(date, a);
document.write(expectedDeliveryDate.toDateString() + ' with Standard Delivery');
}
function addWeekdays(fromDate, days) {
var count = 0;
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate;
}
Also added a timer:
function ShowTime() {
var now = new Date();
var hrs = 15 - now.getHours();
if (hrs < 0) hrs += 24;
var mins = 60 - now.getMinutes();
var secs = 60 - now.getSeconds();
timeLeft = "" + hrs + ' hours ' + mins + ' minutes ' + secs + ' seconds';
$("#countdown").html(timeLeft);
}
var countdown = setInterval(ShowTime, 1000);
function StopTime() {
clearInterval(countdown);
}
I have two sets of 'select' elements where the user can enter in two times. It looks like this:
Start:
[hour] [minute] [meridian]
End:
[hour] [minute] [meridian]
I'm trying to take those times and figure out the difference. So I can then output:
Difference: 1.25 HRS
The decimal format, as you probably know, means 1 hour and 15 minutes.
There's also a checkbox the user can click which, if selected, will take away 30 minutes. Here's what my current code looks like:
var startHours = parseInt($start.find('.times:eq(0)')[0].value);
var startMinutes = parseInt($start.find('.times:eq(1)')[0].value);
var startMeridian = $start.find('.times:eq(2)')[0].value
if (startMeridian == 'PM')
startHours += 12;
var finishHours = parseInt($finish.find('.times:eq(0)')[0].value);
var finishMinutes = parseInt($finish.find('.times:eq(1)')[0].value);
var finishMeridian = $finish.find('.times:eq(2)')[0].value
if (finishMeridian == 'PM')
finishHours += 12;
// compute the difference
var completeHours = finishHours - startHours;
var completeMinutes = finishMinutes - startMinutes;
var newTime = 0;
if (completeHours < 0 || completeMinutes < 0)
newTime = '0.0';
else
newTime = completeHours + '.' + completeMinutes;
var hadBreak = $parent.parents('tr').next('tr').find('.breakTaken')[0].checked;
if (hadBreak)
{
time = newTime.split('.');
hours = time[0];
minutes = time[1];
minutes = minutes - 30;
if (minutes < 0)
{
minutes = 60 - (minutes * 1);
hours = hours - 1;
}
newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;
}
$parent.parents('tr').next('tr').find('.subtotal')[0].innerHTML = newTime;
total += parseFloat(newTime);
It's failing... What am I doing wrong?
To save you some hassle, I would recommend using the Date object, which is very convenient:
var startDate = new Date(year, month, date, hour, minute, second, millisecond);
var endDate = new Date(year, month, date, hour2, minute2, second2, millisecond2);
// You can skip hours, minutes, seconds and milliseconds if you so choose
var difference = endDate - startDate; // Difference in milliseconds
From there you can calculate the days, hours and minutes that passed between those two dates.
The line
newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;
is wrong - minutes might be 15, but you want it to print out the fraction. Hence you need:
var MinutesDisplay = minutes/60*100;
newTime = (hours < 0) ? '0.0' : hours + '.' + (MinutesDisplay.toFixed(0));