I'm using moment.js and would like to create an array that contains all of the times in 15 minute intervals from the current time. So for example:
Current time is 1:35pm. The next time would be 1:45pm, then 2:00, 2:15, 2:30, 2:45, etc. up until a certain point.
I'm really not sure how to this. Would anyone be able to point me in the right direction?
Try this:
function calculate(endTime) {
var timeStops = [];
var startTime = moment().add('m', 15 - moment().minute() % 15);
while(startTime <= endTime){
timeStops.push(new moment(startTime));
startTime.add('m', 15);
}
return timeStops;
}
usage:
calculate(moment().add('h', 1));
This will return time intervals of every quarter of hour (like you said) h:15, h:30, h:45, h+1:00... It also contains seconds, so you might set seconds to 0, since I was not sure if you need them or not.
You also can see working example on FIDDLE
I'm not as familiar with momentjs but this is relatively easy to do in pure Javascript. To get the closest 15 minutes you can use this solution here. Then if you put that in a date variable you can just add 15 minutes as many times as you want! So the resulting Javascript is:
var d = new Date();
var result = "";
for (var idx = 0; idx < 3; idx++)
{
var m = (((d.getMinutes() + 7.5)/15 | 0) * 15) % 60;
var h = ((((d.getMinutes()/105) + .5) | 0) + d.getHours()) % 24;
d = new Date(d.getYear(), d.getMonth(), d.getDay(), h, m, 0, 0);
if (idx > 0) result += ", ";
result += ("0" + h).slice(-2) + ":" + ("0" + m).slice(-2);
d = addMinutes(d, 15);
}
SEE THIS IN A FIDDLE
Notes - I just added 15 minutes 3 times arbitrarily. You could calculate the difference between the time you want and now if you need a different number of intervals. Also note that I don't know exactly what this would do if it is almost midnight, though that would be easy enough to test and code around.
Best of luck!
Related
I'm working on a web timesheet where users use timepicker to determine start & end times and I'd like to have the form automatically find the difference between the two times and place it in a 3rd input box. I understand that I need to get the values, convert them to milliseconds, then subtract the first number from the second, convert the difference back to human time and display that in the third box. But I can't seem to wrap my head around time conversion in javascript. Here's what I have so far:
function date1math(){
var date1in = document.getElementById("date-1-in").value;
var date1out = document.getElementById("date-1-out").value;
date1in = date1in.split(":");
date1out = date1out.split(":");
var date1inDate = new Date(0, 0, 0, date1in[0], date1in[1], 0);
var date1outDate = new Date(0, 0, 0, date1out[0], date1out[1], 0);
var date1math = date1outDate.getTime() - date1inDate.getTime();
var hours = Math.floor(date1math / 1000 / 60 / 60);
date1math -= hours * 1000 * 60 * 60;
var minutes = Math.floor(date1math / 1000 / 60);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
document.getElementById("date-1-subtotal").value = date1math(date1in, date1out);
}
I want to take the timepicker result (say 9:00am) from the input date-1-in, the timepicker result (say 5:00pm) from the input date-1-out, and then place the difference as a number in date-1-subtotal.
Presumably the input is a string in the format hh:mm (e.g. 09:54) and that the two strings represent a time on the same day. You don't mention whether an am/pm suffix is included, but it's there in the text so I'll assume it might be.
If daylight saving changes can be ignored, the simplest method is to convert the string to minutes, find the difference, then convert back to hours and minutes, e.g.:
// Convert hh:mm[am/pm] to minutes
function timeStringToMins(s) {
s = s.split(':');
s[0] = /m$/i.test(s[1]) && s[0] == 12? 0 : s[0];
return s[0]*60 + parseInt(s[1]) + (/pm$/i.test(s[1])? 720 : 0);
}
// Return difference between two times in hh:mm[am/pm] format as hh:mm
function getTimeDifference(t0, t1) {
// Small helper function to padd single digits
function z(n){return (n<10?'0':'') + n;}
// Get difference in minutes
var diff = timeStringToMins(t1) - timeStringToMins(t0);
// Format difference as hh:mm and return
return z(diff/60 | 0) + ':' + z(diff % 60);
}
var t0 = '09:15am';
var t1 = '05:00pm';
console.log(getTimeDifference('09:15am', '05:00pm')); // 07:45
console.log(getTimeDifference('09:15', '17:00')); // 07:45
If daylight saving is to be incorporated, you'll need to include the date so that date objects can be created and used for the time difference. The above can use either 12 or 24 hr time format.
I would like to do the following, given two dates in UTC formatting:
var start = "2014-01-13T06:00:00.0000000Z";
var end = "2014-01-13T14:16:04.0000000Z";
I would like to get the exact time span that passes between these two times, such as
8h 16m
I have tried using the following:
var duration = moment(moment(end) - moment(start)).format('hh[h] mm[m]');
But this does not work with days. Moreover, it does not work with days, since they are always >=1 even if <24 hours pass.
I have also tried twix.js to get the length, but its formatting doesn't support creating the format specified above, or I could not find the way to do so in its documentation. Basically I am looking for an exact version of twix.humanizeLength().
Moment.js's a.diff(b) provides only total durations, it can give me the length of the time span in minutes, hours or days, but not calculated using remainders.
My current solution is to use diff to create the ranges and then use modulo to calculate remainders, but this is not very elegant:
var days = moment(end).diff(start, 'days');
var hours = moment(end).diff(start, 'hours') % 24;
var minutes = moment(end).diff(start, 'minutes') % 60;
var duration = ((days > 0) ? days + 'd ' : '') + ((hours > 0) ? hours + 'h ' : '') + ((minutes > 0) ? minutes + 'm ' : '');
The question: Is there any smarter way to do this in either moment.js or twix.js, or should I take my time and develop my own moment.js plugin?
You can try using Durations, but I'm not sure if those have the capabilities you are looking for http://momentjs.com/docs/#/durations/
Also, you can always user moment's diff to get the difference in milliseconds and then format it to your needs. It is basically the same that you are doing, but you only call diff once.
function convertMilliSecondsIntoLegibleString(milliSecondsIn) {
var secsIn = milliSecondsIn / 1000;
var milliSecs = milliSecondsIn % 1000;
var hours = secsIn / 3600,
remainder = secsIn % 3600,
minutes = remainder / 60,
seconds = remainder % 60;
return ( hours + "h: "
+ minutes + "m: "
+ seconds +"s: " + milliSecs + "ms");
}
There's a plugin for formatting duration in moment.js : moment-duration-format
If it doesn't do what you need, then you should extend moment.duration.fn. If you don't support many locales, it should be easy enough.
In any case, I'd recommend to read the thread of this feature request.
I'm creating a site for my neighbor who has a Christmas light show.
The show runs every year from 6 December till 1 January twice an evening: at 6.30pm and at 8.00pm.
We want to add a countdown on the website which says:
next show: 00:00:00 (hh:mm:ss)
But how do I do that. When I search for it on the web every one says that I have to use an API for a countdown.
But they just use one date to count down to, so I think I have to write one myself in JavaScript.
Can anyone help with that?
I guess I have to use many if/else statements, starting with "is the month 1, 12 or something else?", followed by "has it yet been 18.30?" (I want 24-hours) and "has it already been 20.00" and so on.
But is there a better way, because this seems a lot of work to me.
JavaScript has a built-in date object that makes dealing with dates and times a bit less manual:
MDN documentation for JavaScript's date object
If you supply no arguments to its constructor, it'll give you the current date (according to the end user's computer):
var now = new Date();
You can set it to a specific date by supplying the year, month (zero-indexed from January), day, and optionally hour, minute and second:
var now = new Date();
var first_show = new Date(now.getFullYear(), 11, 6, 18, 30);
You can use greater- and less-than comparisons on these date objects to check whether a date is after or before another:
var now = new Date();
var first_show = new Date(now.getFullYear(), 11, 6, 18, 30);
alert(now < first_show);// Alerts true (at date of writing)
So, you could:
Create date objects for the current date, and each show this year (and for the 1st Jan shows next year)
Loop through the show dates in chronological order, and
Use the first one that's greater than the current date as the basis for your countdown.
Note: you should use something server-side to set now with accurate parameters, instead of just relying on new Date(), because if the end-user's computer is set to the wrong time, it'll give the wrong result.
Here's an example that will count down for 4 hours starting now() :
<script type="text/javascript">
var limit = new Date(), element, interval;
limit.setHours(limit.getHours() + 4);
window.onload = function() {
element = document.getElementById("countdown");
interval = setInterval(function() {
var now = new Date();
if (now.getTime() >= limit.getTime()) {
clearInterval(interval);
return;
}
var diff = limit.getTime() - now.getTime();
var hours = parseInt(diff / (60 * 60 * 1000));
diff = diff % (60 * 60 * 1000);
minutes = parseInt(diff / (60 * 1000));
diff = diff % (60 * 1000);
seconds = parseInt(diff / 1000);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
miliseconds = diff % 1000;
miliseconds = miliseconds.toString().substring(0, 2);
element.innerHTML = hours + ":" + minutes + ":" + seconds + ":" + miliseconds;
}, 10);
}
See it live here
I want change the time on a specified date, i tried as following js code, but doesn't work if... in line number 11. What do i do?
var interval = self.setInterval("clock()", 1000);
function clock() {
var date = new Date();
var hourOffset = 3;
date.setUTCHours(date.getUTCHours(), date.getUTCMinutes());
var time = date.getTime();
date.setUTCFullYear(date.getUTCFullYear(), 3, 21);
var dstStart = date.getTime();
date.setUTCFullYear(date.getUTCFullYear(), 9, 22);
var dstEnd = date.getTime();
if (time > dstStart && time < dstEnd) hourOffset = 4; // This is line 11
date.setUTCHours(date.getUTCHours() + hourOffset, date.getUTCMinutes() + 30);
var output = date.getUTCHours() + ":" + date.getUTCMinutes() + ":" + date.getUTCSeconds();
document.getElementById("clock").innerHTML = output
}
I mean is this line that doesn't work:
if (time > dstStart && time < dstEnd) hourOffset = 4;
DEMO: http://jsfiddle.net/bFzny/
I'm not familiar with the date functions, but I can tell you that time is less than dstStart, which is why hourOffset is staying at 3. Also, months are 0 based indices, not 1 based. March would be 2, while September would be 8. http://jsfiddle.net/bFzny/4/ This might help you some. Remember, when using jsfiddle you don't need to enclose the code in tags.
I need to create a table with just 1 column containing times (starting from 4hrs) which increase in increments of 10 seconds for each row. So it needs to look something like this:
04hrs 00mins 00secs - 04hrs 00mins 09secs
04hrs 00mins 10secs - 04hrs 00mins 19secs
04hrs 00mins 20secs - 04hrs 00mins 29secs
.....
06hrs 59mins 50secs - 06hrs 59mins 59secs
This will obviously take a long long time to hard code so I'm looking to create it dynamically. Based on what i'm currently trying to learn I'd like to be able to do this using jquery or asp.net (vb) but anything will do as long as it works!
Thanks
Basic date-time arithmetic.
// format the given date in desired format
// ignores date portion; adds leading zeros to hour, minute and second
function fd(d){
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
return (h < 10 ? '0'+h : h) + 'hrs ' +
(m < 10 ? '0'+m : m) + 'mins '+
(s < 10 ? '0'+s : s) + 'secs';
}
// 1) 10800 seconds = 3600 * 3 = 3 hours
// 2) a+=10 increments seconds counter in 10-second interval
for ( var a = 0; a < 10800; a+=10 ) {
// an arbitrary date is chosen, we're more interested in time portion
var b = new Date('01/01/2000 04:00:00');
var c = new Date();
b.setTime(b.getTime() + a*1000);
// c is b + 9 seconds
c.setTime(b.getTime() + 9*1000);
$("#table1").append(
"<tr><td>" + fd(b) + ' - ' + fd(c) + "</td></tr>"
);
}
See the output here. I think you can port this code example to ASP.Net/VB.Net/C# easily.