So there's plenty of examples on how to calculate the time between two dates.
But in my case, I have a date X. Let's say it's today.
X has a time associate to it, e.g. 08:00 (Or what I get back from .getHours())
I need to know if the hours of X are between a start hour (say "07:00") and an end hour (say "12:00")
X will be always retrieved via getHours()
The start and end hour of the range have a fixed format (e.g. "07:00" and "12:00")
Performance is an issue, so whatever performs better is preferred (e.g. if it implies using moment, that's fine, but if a custom function would perform better, we want that)
My first approach would be, as the formats are fixed, to transform the .getHours() to a number, likewise for the range hours, and then calculate...I feel this approach my have trouble with some special cases I may not be aware of?
You could use moment-range
From docs:
You can also create a range from an ISO 8601 time interval string:
var timeInterval = "2015-01-17T09:50:04+00:00/2015-04-17T08:29:55+00:00";
var range = moment.range(timeInterval);
range.contains(X); // true if between interval
If you want to check part hours, consider converting the hours to minutes, something like the following. How will you deal with ranges that go over midnight? e.g. 23:30 to 01:30.
/* Determine if the current time is between two provided hours
** #param {string} h0 - time in format h:mm
** #param {string} h1 - time in format h:mm
** #returns {boolean} true if the current time is between or equal to h0 and h1
*/
function betweenHours(h0, h1) {
var now = new Date();
var mins = now.getHours()*60 + now.getMinutes();
return toMins(h0) <= mins && mins <= toMins(h1);
}
/* Convert hours to minutes
** #param {string} h - time in format h:mm
** #returns {number} time converted to minutes
*/
function toMins(h) {
var b = h.split(':')
return b[0]*60 + +b[1];
}
<form>
Start time (h:mm)<input name="startHours">
<br>
End time (h:mm)<input name="endHours">
<br>
<button type="button" onclick="
this.form.inRange.value = betweenHours(this.form.startHours.value, this.form.endHours.value);
">Check range</button>
<br>
Currently in range? <input name="inRange" readonly>
</form>
Are you dealing with military tine? (From 0:00 to 24:00)
getHours() returns an Integer, and if you are only interested in hours and not minutes, you can use parseInt() to turn the start and end hours into integers as well. For example, parseInt('07:00', 10) will return 7. So if you wanted to create a function to test if the current time is between two hours, it might look something like this:
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('07:00', '12:00') ) { //some code here }
Related
I've divided a day into 8 ticks of three hours each. When making this range it goes from 00:00 to 21:00, and not until 00:00 again.
const startDate = new Date("2021-03-14T23:00:00.000Z");
const endDate = new Date("2021-03-15T23:00:00.000Z");
const dayInThreeHourPeriods = d3.timeHour.every(3).range(startDate, endDate);
dayInThreeHourPeriods.forEach((period) => {
console.log(`period: ${format(period, 'HH:mm')}`);
});
// outputs
// from: 00:00
// to: 21:00
// would like it to go to 24:00
How can I change this so that it goes to 24:00?
I want to use it for an axis:
Made a working example here: https://jsfiddle.net/Spindle/kfL5oh12/21/
This is intended from the .range method, as d3.timeHour.every is just an alias to interval.range;
From d3-time docs:
interval.range(start, stop[, step]) · Source
Returns an array of dates representing every interval boundary after or equal to start (inclusive) and before stop (exclusive). If step is specified, then every stepth boundary will be returned; for example, for the d3.timeDay interval a step of 2 will return every other day. If step is not an integer, it is floored.
As you've already stated in your own answer, it seems like a known issue.
Anyway, why don't use write your own logic to divide the day into 3-hours chunks? This way we don't need to rely on d3d3's .range method;
let startDate = new Date("2021-03-14T23:00:00.000Z");
let endDate = new Date("2021-03-15T23:00:00.000Z");
var dayInThreeHourPeriods = [ startDate ];
while (endDate > startDate) {
startDate = new Date(startDate.getTime() + (60 * 60 * 3 * 1000));
dayInThreeHourPeriods.push(startDate);
}
console.log(dayInThreeHourPeriods);
Updated JSFiddle
Turns out this is a known issue.
What people tend to do is add a small time period and suddenly it's inclusive:
d3.range(min, max+0.001)
or in my case:
const dayInThreeHourPeriods = d3.timeHour.every(3).range(startDate, d3.timeHour.offset(endDate, 1));
Not ideal. Look there's a proposal to have 'rangeInclusive' which would be better already. But there is no activity on that issue.
If anyone has a better idea for the time being I'd be interested.
I have this JS script:
if ($('.count-down').length !== 0){
$('.count-down').countdown({
timestamp : (new Date()).getTime() + 24*60*60*1000
});
}
It provides +24 hours as 24*60*60*1000 so script starts count down from 24:00:00
I need to give this script my event date as valuable format Y.m.d H:i I.E. 2014.12.31 12:00, that it would calculate the time difference between now and add it to the code.
var difference = getTimeDifferenceFromNow('2014.12.31 12:00')
timestamp : (new Date()).getTime() + difference
Substract two Date instances, you will get the length between in millisecond.
function getTimeDifferenceFromNow(timeString) {
return new Date(timeString) - new Date();
}
getTimeDifferenceFromNow('2014.12.31 12:00') // 818501769, roughly 9 days and half in the future.
How could this work? When you substract two Date instances, their valueOf() method is called internally, which will convert them to timestamp. Then you are actually subsctracting two timestamps, finally get a number of millisecond.
EDIT
However, I was wondering why you did in that way? If you want the timestamp of a given date/time, why don't you just instantiate it and grab its timestamp?
new Date('2014.12.31 12:00').getTime() // 1419998400000
This was the final solution:
var eventdate = new Date("January 1, 2015 1:00:00").getTime();
if ($('.count-down').length !== 0){
$('.count-down').countdown({
timestamp : eventdate
});
}
I know how to use javascript, but i have no in depth knowledge of it. I know how I can get the date difference in days in PHP but in this case, I need javascript solution. Honestly, i don't even know if it is possible, to do this with Javascript. I guess that it is,but that is just a guess.
Here is the html that I have:
<div class="span3" id="checkin">
<span class="text-label"><i class="icon-calendar"></i>Check In</span>
<input type="text" name="checkin" value="02/08/2014">
</div>
<div class="span3" id="checkout">
<span class="text-label"><i class="icon-calendar"></i>Check Out</span>
<input type="text" name="checkout" value="04/08/2014">
</div>
Those two fields are actually bootstrap date pickers. They always come with some default values. Now, I want when user change those two values to calculate the difference between two dates (alert or console log will do, I will find my way from there).
Problem is that I have no clue where to start and how to do that calculation. Again I guess that onchange event may be a good candidate but...I have no idea how to calculate the difference.
Any help will be deeply appreciated.
Regards, John
You could first parse your string an create a JavaScript date like that:
var start = $("input[name=checkin]").val().split("/");
var end = $("input[name=checkout]").val().split("/");
var startDate = new Date(start[2], start[1]-1, start[0]);
var endDate = new Date(end[2], end[1]-1, end[0]);
Then you can simply substract the dates from each other:
endDate - startDate
That substraction will give you the time difference in milliseconds. To convert that to days, simply divide it by the number of milliseconds in a day (1000 * 60 * 60 * 24).
Now you have the difference in days. For an example, see JSFiddle.
<script type="text/javascript">
//Set the two dates
today=new Date()
var christmas=new Date(today.getFullYear(), 11, 25) //Month is 0-11 in JavaScript
if (today.getMonth()==11 && today.getDate()>25) //if Christmas has passed already
christmas.setFullYear(christmas.getFullYear()+1) //calculate next year's Christmas
//Set 1 day in milliseconds
var one_day=1000*60*60*24
//Calculate difference btw the two dates, and convert to days
document.write(Math.ceil((christmas.getTime()-today.getTime())/(one_day))+
" days left until Christmas!")
This short Javascript will display the DAY difference between today (value 1) and christmas (your value 2). Ovbioulsy these can be replaced with our two values and should then work.
Example: 146 days left until Christmas!
var date1 = new Date("7/11/2010");
var date2 = new Date("12/12/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
Try this . i found it from this link
I have created a small function that i need on my site successfully in php. But i now realise i actually need this in javascript or jquery as PHP will only excute this code on load.. i need this function to work with onchange on a select. The code below is my function.. Can anyone point out where i start to convert this into js/jquery like code:
function setTrnTime ($hr, $journeyTime){
date_default_timezone_set('GMT');
//convert current hour to time format hour
$currentHour = (date("H", mktime($hr)));
// Journey time in hours
$journey = $journeyTime
$journey = $journey/60; // Get hours
$journey = ceil($journey); // Round off to next hour i.e. 3 hours 20mins is now 4 hours
// New Hours
$NewHour = (date("H", mktime($journey)));
$Newhour = $NewHour*60*60; // convert to seconds
// Final hour is Current Hour - JourneyTime (Hours)
$trnHour = (date('H', mktime($currentHour-$NewHour)));
return $trnHour;
}
With the code above, if i pass two values 06, 60: that would mean my answer would be 05. e.g. 06 is 6am. 60 is 60mins.. so 6am - 60mins = 5am.
You can do the same in javascript using the Date object, see info here
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
EDITED: Added some code, also not even using the Date object.
But do you need something that complex, doesn't the following do what you are after with less steps.
http://jsfiddle.net/WWTDc/
If hr is a Date object, then it's very simple. Otherwise you can create a Date object and set its hour:
//! \param[in] hr Date object or hour (0--23)
//! \param[in] journeyTime journey time in minutes.
function setTrnTime(hr,journeyTime){
var end;
if(typeof(hr) === 'number'){
end = new Date();
end.setHours(hr);
}
else
end = hr;
return (new Date(end - journeyTime*60*1000)).getHours();
}
This will return the hour (demonstration).
See here for information about Date object in JavaScript.
I'm looking for a HTML code that adds a fixed number of days to an entered Date of Birth. Thanks a lot! Even a partial code is much appreciated!
Here is how I'd do it. The function daysFromDate returns a Date object you can use. Instead of passing the DOB as a string you can also update it to use a Date object.
/*
days is the number of days to add, and dob a string like "4/24/2011"
*/
function daysFromDate(days, dob) {
var dates = dob.split('/');
var daysToMilli = days * 60 * 60 * 24 * 1000;
var d = new Date(parseInt(dates[2]), parseInt(dates[0])-1, parseInt(dates[1]));
var newTime = d.getTime() + daysToMilli;
return new Date(newTime);
}
To get the date 20 days from now you call: daysFromDate(20, "4/24/2011");
VBScript has DateAdd() so it's pretty simple. If you prefer JavaScript, just Google "javascript dateAdd" -- there are a zillion solutions out there. Here's one:
http://www.solutionbot.com/2008/06/20/javascript-dateadd-function/