How to add 15 minutes to custom timer - Javascript - 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 ":".

Related

Difference between two dates by using angularjs?

This is my code
var departureDateFormat = new Date("10/09/15T09:25:00");
var arrivalDateFormat = new Date("13/09/15T13:25:00");
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[2];
var duration = moment.duration(arrivalDateFormat - departureDateFormat); //for reference of moment.js
var minutes = (duration / (1000 * 60)) % 60; // calliculating number of minutes
var hours = ((moment.duration(arrivalDateFormat - departureDateFormat)).humanize()); // calliculating number of hours
var timeInHours = ((hours == "an hour") ? 1 : hours.toString().substring(0, 1));
item.stopsDurationTime = timeInHours + "hrs " + minutes + "ms";
return timeInHours + "hrs " + minutes + "ms";
In the above code worked on IE , but it was not working on other browsers.Now i want to get difference between the above two dates by using angularJs/javascript.
You should use:
var minutes = duration.minutes();
var hours = duration.hours();
return hours + "hrs " + minutes + "ms";
Humanizing and then extracting the individual values is just unneeded overhead.
And moment can extract the hours and minutes for you so no need to compute from milliseconds.
Update:
Something like this:
var departureDate = moment("10/09/15T09:25:00", "DD/MM/YYYYTHH:mm:ss");
var arrivalDate = moment("13/09/15T13:35:10", "DD/MM/YYYYTHH:mm:ss");
var duration = moment.duration(arrivalDate.diff(departureDate));
var hours = Math.floor(duration.asHours());
var minutes = Math.floor(duration.asMinutes()-(hours*60));
return hours + "hrs " + minutes + "ms";
You have to define the format explicitly otherwise depending on your regional setting it will understand "10/09" as October, 9th or September, 10th.
Then you create a duration object. And you convert it to a number of hours (using "floor" to get a whole number). Then you convert it again to a number of minutes and subtract the hours you already got.

Javascript/PHP countdown timer that updates every second and counts down to a specific date and time

So the code below is the code that I was able to work with so far; however, doesn't do exactly what I need it to do.
I want to be able to call a function (aka: sundayDelta() ), however, I would love to be able to define the day of week and time of day I want the function to use in the countdown inside the calling of the function. I'm not sure if this is possible...but I was thinking something like this
sundayDelta(1,1000) which would turn into Day of Week Sunday and time of day: 1000 (10:00am). Not sure if something like this is even possible; however, I'm hoping it is. I plan on having multiple countdowns going on the same page just appearing at different times of day.
When the countdown finishes, I want it to refresh a div (doesn't matter what name the div has)
I would also love to be able to incorporate PHP server time into this that way everyone is seeing the correct countdown no matter where they are.
Any help would be great! Thanks for your input!
function plural(s, i) {
return i + ' ' + (i > 1 ? s + 's' : s);
}
function sundayDelta(offset) {
// offset is in hours, so convert to miliseconds
offset = offset ? offset * 20 * 20 * 1000 : 0;
var now = new Date(new Date().getTime() + offset);
var days = 7 - now.getDay() || 7;
var hours = 10 - now.getHours();
var minutes = now.getMinutes() - 00 ;
var seconds = now.getSeconds()- 00;
if (hours < 0){
days=days-1;
}
var positiveHours= -hours>0 ? 24-(-hours) : hours;
return [plural('day', days),
plural('hour', positiveHours),
plural('minute', minutes),
plural('second', seconds)].join(' ');
}
// Save reference to the DIV
$refresh = $('#refresh');
$refresh.text('This page will refresh in ' + sundayDelta());
// Update DIV contents every second
setInterval(function() {
$refresh.text('This page will refresh in ' + sundayDelta());
}, 1000);
When I make flexible text for intervals, I like to subtract out until nothing is left. That way you only show the non-0 values:
function sundayDelta(target_date) {
var now = new Date();
var offset = Math.floor((Date.parse(target_date) - now.valueOf()) / 1000);
var r = [];
if (offset >= 86400) {
var days = Math.floor(offset / 86400);
offset -= days * 86400;
r.push(plural('day', days));
}
if (offset >= 3600) {
var hours = Math.floor(offset / 3600);
offset -= hours * 3600;
r.push(plural('hour', hours));
}
if (offset >= 60) {
var minutes = Math.floor(offset / 60);
offset -= minutes * 60;
r.push(plural('minute', minutes));
}
if (offset != 0) {
r.push(plural('second', offset));
}
return r.join(' ');
}
In the PHP code, you can set variable this way. And we'll leave time zones out of it for now, but they could be added as well just by specifying them.
echo "target_date = '" . date('Y-m-d H:i:s', strotime('next Sunday 10am')) . "';\n";

How to multiply time using javascript?

I have the following timespan coming from a model in MVC:
timeTaken = "00:01:00";
Then I have a multiplier
multiply = "3";
Result: 00:03:00
What would be the best way to calculate this time?
I don't know a great deal of libraries. I was thinking of splitting the seconds, minutes and hours, dividing each one into seconds, multiplying then putting it back together.
However, I have this kind of calculations for many sections, it just seems a little mundane. Can I just multiply the time in a better manner?
Thanks
I am combining the snippets I found in multiple pages. Conversion of hh:mm:ss to seconds, multiply 3x and then again convert to hh:mm:ss.
var hms = '00:01:00'; // your input string
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var newSeconds= 3*seconds;
// multiply by 1000 because Date() requires miliseconds
var date = new Date(newSeconds * 1000);
var hh = date.getUTCHours();
var mm = date.getUTCMinutes();
var ss = date.getSeconds();
// If you were building a timestamp instead of a duration, you would uncomment the following line to get 12-hour (not 24) time
// if (hh > 12) {hh = hh % 12;}
// These lines ensure you have two-digits
if (hh < 10) {hh = "0"+hh;}
if (mm < 10) {mm = "0"+mm;}
if (ss < 10) {ss = "0"+ss;}
// This formats your string to HH:MM:SS
var t = hh+":"+mm+":"+ss;
document.write(t);
JSFiddle
First you can convert them to seconds as below
var hms = "00:01:00";
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var newSeconds=seconds * 3;
var t = new Date();
t.setSeconds(newSeconds);
console.log(t);
DEMO
Update
To just obtain time do as below
var time=t.toTimeString().split(' ')[0]
DEMO
UPDATE
To obtain just hour from time you can do as follows
t.toTimeString().split(' ')[0].split(':')[0]
and to obtain hour in 12 hour format you can do as below:
var hour;
if(t.toTimeString().split(' ')[0].split(':')[0]>12)
hour=t.toTimeString().split(' ')[0].split(':')[0]-12;
else
hour=t.toTimeString().split(' ')[0].split(':')[0];
alert(hour);
UPDATED DEMO

Why do I get +1 hour when calculating time difference in javascript?

I trying to create a very simple time difference calculation. Just "endtime - starttime". I'm getting +1 hour though. I suspect it has with my timezone to do, since I'm GMT+1.
Regardless, that should not affect the difference, since both start and end times are in the same timezone.
Check my running example-code here:
http://jsfiddle.net/kaze72/Rm3f3/
$(document).ready(function() {
var tid1 = (new Date).getTime();
$("#tid").click(function() {
var nu = (new Date).getTime();
var diff = new Date(nu - tid1);
console.log(diff.getUTCHours() + ":" +
diff.getUTCMinutes() + ":" +
diff.getUTCSeconds());
console.log(diff.toLocaleTimeString());
});
})
You must understand what Date object represent and how it stores dates. Basically each Date is a thin wrapper around the number of milliseconds since 1970 (so called epoch time). By subtracting one date from another you don't get a date: you just get the number of milliseconds between the two.
That being said this line doesn't have much sense:
var diff = new Date(nu - tid1);
What you really need is:
var diffMillis = nu - tid1;
...and then simply extract seconds, minutes, etc.:
var seconds = Math.floor(diffMillis / 1000);
var secondsPart = seconds % 60;
var minutes = Math.floor(seconds / 60);
var minutesPart = minutes % 60;
var hoursPart = Math.floor(minutes / 60);
//...
console.log(hoursPart + ":" + minutesPart + ":" + secondsPart);
Working fiddle.

Calculating time diference in JavaScript (days+hours+minutes+seconds)

lol sorry i posted it accidentally
I'm new to JavaScript and i'm trying to make a simple countdown script that should show the difference between the end date and today's server date.
here is a great example of what i'm trying to do http://moblog.bradleyit.com/2009/06/javascripting-to-find-difference.html
The only thing i want to add is another variable with a calculated seconds. How can i do that?
Here is the code:
var today = new Date();
var Christmas = new Date("12-25-2009");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.round(diffMs / 86400000); // days
var diffHrs = Math.round((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
alert(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas 2009 =)");
You have two issues with this code:
1: You need to use a date that will be accepted across browsers so it needs to be formatted with / instead of -.
2: You are rounding, which when rounding up will give you inaccurate numbers. All numbers need to be rounded down. Here is a function do do so:
var roundDown = function(num){
var full = num.toString();
var reg = /([\d]+)/i;
var res = reg.exec(full);
return res[1];
}
So your final code should look like this:
var roundDown = function(num){
var full = num.toString();
var reg = /([\d]+)/i;
var res = reg.exec(full);
return res[1];
}
var today = new Date(); // date and time right now
var goLive = new Date("06/01/2013"); // target date
var diffMs = (goLive - today); // milliseconds between now & target date
var diffDays = roundDown(diffMs / 86400000); // days
var diffHrs = roundDown((diffMs % 86400000) / 3600000); // hours
var diffMins = roundDown(((diffMs % 86400000) % 3600000) / 60000); // minutes
var diffSecs = roundDown((((diffMs % 86400000) % 3600000) % 60000) / 1000 ); // seconds
var endDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);
var today = Date.now()
var timeLeft = endDate - today // timeLeft would be in milliseconds
// Parse this into months, days, hours, ...
Put this in a function and set it up to be called every second or so using setInterval.
This should get you started with the JavaScript date object and it's associated methods.
http://www.w3schools.com/jsref/jsref_obj_date.asp
Also, look up the setInterval() method, that will allow you to fire code in set intervals (for example, updating the countdown text).

Categories

Resources