javascript adding minutes in a loop - javascript

Can't figure this out, from 9:00 to 10:00 everything's correct, but then it all goes haywire. after 10:00 it jumps to 11:15 and then to 12:30
I am simply adding minutes to a date/time to increment an array in 15 minute intervals, is it that I can only add a maximum of 60 minutes ??
function pad(val,max) {
var str = val.toString();
return str.length < max ? pad("0" + str, max) : str;
}
function cboHrs(){
var now = new Date();
now.setHours(9);
var hrs = [];
for (var i=1;i<36;i++){
var hr = {};
now.setMinutes(i*15);
hr.txt = pad(now.getHours(),2) +':'+pad(now.getMinutes(),2);
hr.val = hr.txt;
hrs.push(hr);
}
return hrs;
}
console.log(cboHrs());

Anthony got to the actual problem before me...
After the 5th iteration, you are setting the minutes to become 75 (ie,
5 * 15 = 75) which is an 1 hour and 15 minutes which is why the next
value after 10:00 becomes 11:15
- Anthony Forloney
This code should work to set the time correctly.
function cboHrs(){
var now = new Date();
var hrs = [];
for (var i=1;i<36;i++){
var hr = {};
// add another hour every 4th iteration
now.setHours(9 + parseInt(i / 4));
// add 15 minutes every iteration, starting back at 0 on the 4th
now.setMinutes((i % 4) * 15);
hr.txt = pad(now.getHours(),2) +':'+pad(now.getMinutes(),2);
hr.val = hr.txt;
hrs.push(hr);
}
return hrs;
}

The problem lies within the now.setMinutes(i*15); line of code. After the 5th iteration, you are setting the minutes to become 75 (ie, 5 * 15 = 75) which is an 1 hour and 15 minutes which is why the next value after 10:00 becomes 11:15

Related

How to get the remaining time from 24 hours in JavaScript

I have a problem, where I try to find the number of hours and minutes after I had last collected the item. For example, if I had collected the item 1 minute ago, the code should be able to print out the remaining time left to collect the item again(23 h and 59 m) in this format. Till now, I have worked out this much:
UserJSON is a JSON file with the user's name and the time of their last claim
let deltaHour = Math.floor(new Date().getTime() - UserJSON[message.author.id].lastclaim) / (60 * 60 * 24)
let deltaRealHour = Math.floor(deltaHour)
let deltaMin = ((deltaHour % 1) / 100) * 60
Please help me out.
Here is a possible solution.
You can use the function I wrote before (timeUntilNextClaim()), supply it with the last time that your user claimed the item (in epoch seconds) and it will return to you the delta milliseconds until the item can be claimed.
You can then use the second funciton I wrote for you (toHrsAndMinutes) to turn milliseconds into hours and minutes (rounded down of course).
Please let me know if you have any questions or would like any more help with this. I'd be happy to help.
function timeUntilNextClaim(LastClaim) {
/* this function takes an epoch time of the
last time the user claimed the item as an argument and
returns (in ms) the time until they can pick up the
item again */
let now = new Date();
// add 24 hours to last claim time to calculate next claim time
let timeTilClaim = (LastClaim + 8.64e7) - now;
if (timeTilClaim <= 0) {
return 0;
} else {
return timeTilClaim;
}
}
function toHrsAndMinutes(duration) {
// this function will return an array of [hours, minutes] of a duration specified in ms
var hours, minutes;
hours = Math.floor(duration / 3.6e6);
minutes = Math.floor((duration % 3.6e6) / 60000);
return [hours, minutes];
}
function test() {
// tests / Example Usage
let usrLastClaimTime = new Date() - 20160000; // lets pretend they claimed it last 5.6 hours ago
let now = new Date();
let msTilNextClaim = timeUntilNextClaim(usrLastClaimTime);
let hoursTilClaim, minsTilClaim;
[hoursTilClaim, minsTilClaim] = toHrsAndMinutes(msTilNextClaim);
console.log(`The current time is ${now}`);
console.log(`The item was last claimed at ${Date(usrLastClaimTime)}`);
console.log(`You can claim again in ${hoursTilClaim} Hours and ${minsTilClaim} Minutes`);
}
test();
getTime() is milliseconds since Jan 1, 1970, 00:00:00.000 GMT
let lastclaim = 1632196398605;
let delta = (new Date() - new Date(lastclaim)) / (60 * 1000 * 60);
let deltaHrs = Math.floor(delta);
let deltaMins = Math.floor((delta % 1) * 60);
console.log(`deltaHrs:`, deltaHrs);
console.log(`deltaMins:`, deltaMins);

Time difference in javascript

var time_1 = '13:44:25:912';
var time_2 = '14:45:30:910';
var inTime=time_1.split(":");
var outTime= time_2.split(":");
var hr = outTime[0] - inTime[0];
var min = ((outTime[1] - inTime[1])+hr*60)%60;
var sec = ((outTime[2] - inTime[2])+min*60)%60;
var milli = ((outTime[3] - inTime[3])+sec*1000)%1000;
document.write(milli);
document.write("<br>"+sec);
document.write("<br>"+min);
document.write("<br>"+hr);
Hey Friends I am need to find time difference in milliseconds I am able to get the difference in HH:MM:SS:Milli now i have convert all into milli plz help for the same
total milliseconds would be milli + (sec * 1000) + (min * 60000) + (hr * 3600000)
You can use the Date.parse function to get the number of milliseconds since January 1, 1970, 00:00:00 UTC. You need to pass a date-part to the string, but it doesn't really matter as long as you keep it the same in both strings.
JavaScript
var time1 = Date.parse("01 Jan 2000 13:44:25:912"),
time2 = Date.parse("01 Jan 2000 14:45:30:910");
console.log(time2 - time1);
Output
3664998
See jsFiddle

How to get time difference between two timestamps in seconds with jQuery?

I want to display x seconds ago based on a MySQL Timestamp.
I found the plugin called timeago
But I cannot find a way to make it display only seconds.
I'm OK with 61 seconds, or 300 seconds. Any way to convert the output to seconds with timeago, or with pure jQuery / JavaScript ?
Thanks for any help !
Edit:
Sample Case :
$time1 = "2014-02-02 23:54:04"; // plus PHP ways to format it.
//$time2 = NOW() , or date(); whatever.
I just want to get how many seconds since $time1.
Edit 2:
Working code :
<script type="text/javascript">
$(function(){
var d2 = new Date();
var d1 = new Date("2014-02-02 23:54:04");
$("a#timedif").html("Diff. Seconds : "+((d2-d1)/100).toString());
// note that you may want to round the value
});
</script>
It outputs Diff. Seconds : NaN
assuming you parse the string into JavaScript date object, you can do
(date2 - date1)/1000
to parse mysql format timestamp, just feed the string into new Date():
var d2 = new Date('2038-01-19 03:14:07');
var d1 = new Date('2038-01-19 03:10:07');
var seconds = (d2- d1)/1000;
fix of edit 2 in the question:
<script type="text/javascript">
$(function(){
var d2 = new Date();
var d1 = new Date("2014-02-02 23:54:04");
$("a#timedif").html("Diff. Seconds : "+((d2-d1)/1000).toString());
});
If you are okay with that plugin you can modify it a little bit to work with seconds only
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
seconds < 90 && substitute($l.minute, 1) ||
minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
minutes < 90 && substitute($l.hour, 1) ||
hours < 24 && substitute($l.hours, Math.round(hours)) ||
hours < 42 && substitute($l.day, 1) ||
days < 30 && substitute($l.days, Math.round(days)) ||
days < 45 && substitute($l.month, 1) ||
days < 365 && substitute($l.months, Math.round(days / 30)) ||
years < 1.5 && substitute($l.year, 1) ||
substitute($l.years, Math.round(years));
with this part, go only with converting to seconds
see the fiddle: http://jsfiddle.net/zGXLU/1/
jQuery is just a JavaScript library so JavaScript will just work within your jQuery script:
// specified date:
var oneDate = new Date("November 02, 2017 06:00:00");
// number of milliseconds since midnight Jan 1 1970 till specified date
var oneDateMiliseconds = oneDate.getTime();
// number of milliseconds since midnight Jan 1 1970 till now
var currentMiliseconds = Date.now();
// return time difference in milliseconds
var timePassedInMilliseconds = (currentMiliseconds-oneDateMiliseconds)/1000;
alert(timePassedInMilliseconds);
My working with time difference for calculating each value separately
var start = new Date('Mon Jul 30 2018 19:35:35 GMT+0500');
var end = new Date('Mon Jul 30 2018 21:15:00 GMT+0500');
var hrs = end.getHours() - start.getHours();
var min = end.getMinutes() - start.getMinutes();
var sec = end.getSeconds() - start.getSeconds();
var hour_carry = 0;
var minutes_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
}
hrs = hrs - hour_carry;
if(sec < 0){
sec += 60;
minutes_carry += 1;
}
min = min - minutes_carry;
console.log("hrs",hrs);
console.log("min",min);
console.log("sec",sec);
console.log(hrs + "hrs " + min +"min " + sec + "sec");
Get difference between two timestamps in
Seconds: (get timestamp by new Date().getTime())
diff_in_time = (timestamp_1 - timestamp2);
In Days:
diff_in_days = parseInt((timestamp_1 - timestamp2) / (1000 * 3600 * 24));

How to add 15 minutes to custom timer - Javascript

I've got this js:
<script>
$('#appt_start').val(parent.location.hash);
$('#appt_end').val(parent.location.hash);
</script>
which gets the hash value from the url something.com/diary.php#0800 for example.
The value is then used to autofill the start and end times in an appointment form.
I need the second time (#appt_end) to be incremented by 15 minutes? Any ideas how I do this, my js is rubbish...
Thanks!
EDIT
Here's the working code I'm now using:
// add the time into the form
var hashraw = parent.location.hash;
var minIncrement = 15; // how many minutes to increase
hash = hashraw.replace("#", ""); // remove the hash
// first we split the time in hours and mins
var hours = parseInt(hash.substring(0, 2),10); // get hours (first 2 chars)
var mins = parseInt(hash.substring(2, 4),10); // get mins (last 2 chars)
// add the new minutes, and enforce it to fit 60 min hours
var newMins = (mins + minIncrement )%60;
// check if the added mins changed thehour
var newHours = Math.floor( (mins + minIncrement ) / 60 );
// create the new time string (check if hours exceed 24 and restart it
// first we create the hour string
var endTime = ('0' + ((hours+newHours)%24).toString()).substr(-2);
// then we add the min string
endTime += ('0'+ newMins.toString()).substr(-2);
$('#appt_start').val(hash);
$('#appt_end').val( endTime );
You need to split the time in hours / mins and then apply time logic to it to increase it..
var hash = parent.location.hash.replace('#','');
var minIncrement = 15; // how many minutes to increase
// first we split the time in hours and mins
var hours = parseInt(hash.substring(0, 2),10); // get hours (first 2 chars)
var mins = parseInt(hash.substring(2, 4),10); // get mins (last 2 chars)
// add the new minutes, and enforce it to fit 60 min hours
var newMins = (mins + minIncrement )%60;
// check if the added mins changed thehour
var newHours = Math.floor( (mins + minIncrement ) / 60 );
// create the new time string (check if hours exceed 24 and restart it
// first we create the hour string
var endTime = ('0' + ((hours+newHours)%24).toString()).substr(-2);
// then we add the min string
endTime += ('0'+ newMins.toString()).substr(-2);
$('#appt_start').val( hash );
$('#appt_end').val( endTime );
Check it out at http://www.jsfiddle.net/gaby/cnnBc/
try this:
<script>
$(function() {
$('#appt_start').val(parent.location.hash);
var end = parent.location.hash;
end = end.replace("#", "");
end = (end * 1) + 15;
if (end < 1000) {end = '0' + end};
$('#appt_end').val(end);
});
</script>
Would it be possible like this?
Working Demo
var hash="08:00";
$('#appt_start').val(hash);
var d = new Date("October 13, 1975 "+hash)
d.setMinutes(d.getMinutes()+15);
$('#appt_end').val(d.getHours()+":"+d.getMinutes());
You use a fictitious date so to sum the minutes.
If the hash has not the ":", you can do a substring to insert the ":".

Javascript, Hour comparisson

Having two strings (start and end time) in such form "16:30", "02:13" I want to compare them and check if the gap is greater than 5 mins.
How can this be achieved in Javascript in an easy way?
function parseTime(time) {
var timeArray = time.split(/:/);
// Using Jan 1st, 2010 as a "base date". Any other date should work.
return new Date(2010, 0, 1, +timeArray[0], +timeArray[1], 0);
}
var diff = Math.abs(parseTime("16:30").getTime() - parseTime("02:13").getTime());
if (diff > 5 * 60 * 1000) { // Difference is in milliseconds
alert("More that 5 mins.");
}
Do you need to wrap over midnight? Then this is more difficult. For example, 23:59 and 00:01 will produce a difference of 23 hours 58 minutes and not 2 minutes.
If that's the case you need to define your case more closely.
You can do as following:
if (((Date.parse("16:30") - Date.parse("02:13")) / 1000 / 60) > 5)
{
}
// time is a string having format "hh:mm"
function Time(time) {
var args = time.split(":");
var hours = args[0], minutes = args[1];
this.milliseconds = ((hours * 3600) + (minutes * 60)) * 1000;
}
Time.prototype.valueOf = function() {
return this.milliseconds;
}
// converts the given minutes to milliseconds
Number.prototype.minutes = function() {
return this * (1000 * 60);
}
Subtracting the times forces the object to evaluate it's value by calling the valueOf method that returns the given time in milliseconds. The minutes method is another convenience method to convert the given number of minutes to milliseconds, so we can use that as a base for comparison throughout.
new Time('16:30') - new Time('16:24') > (5).minutes() // true
This includes checking whether midnight is between the two times (as per your example).
var startTime = "16:30", endTime = "02:13";
var parsedStartTime = Date.parse("2010/1/1 " + startTime),
parsedEndTime = Date.parse("2010/1/1 " + endTime);
// if end date is parsed as smaller than start date, parse as the next day,
// to pick up on running over midnight
if ( parsedEndTime < parsedStartTime ) ed = Date.parse("2010/1/2 " + endTime);
var differenceInMinutes = ((parsedEndTime - parsedStartTime) / 60 / 1000);
if ( differenceInMinutes > 5 ) {
alert("More than 5 mins.");
}

Categories

Resources