I'm trying to use getHours and getMinutes to use them on a later function. The problem is that I always want the final number to be 3 or 4 digit and 2 digit. What happens is when the minutes are 0-9 the result of 1:04 is 14. This is my code and it doesn't fix the problem.
$hours = (new Date).getHours(),
$mins = (new Date).getMinutes();
function addZero($hours) {
if ($hours < 10) {
$hours = "0" + $hours;
}
return $hours;
}
function addZero($mins) {
if ($mins < 10) {
$mins = "0" + $mins;
}
return $mins;
}
$nowTimeS = $hours + "" + $mins;
// Convert string with now time to int
$nowTimeInt = $nowTimeS;
Problem is that you have two functions with same name, but you never call that function:
$date = new Date();
$hours = $date.getHours(),
$mins = $date.getMinutes();
$nowTimeS = addZero($hours) + "" + addZero($mins);
// Convert string with now time to int
$nowTimeInt = $nowTimeS;
function addZero($time) {
if ($time < 10) {
$time = "0" + $time;
}
return $time;
}
You defined your function twice using the same name and never called it
Perhaps you are looking for this?
function pad(num) {
return ("0"+num).slice(-2);
}
var d = new Date(),
hours = d.getHours(),
mins = d.getMinutes(),
nowTimeS = pad(hours) + ":" + pad(mins);
console.log(nowTimeS)
Related
i am trying to find the difference for end time and start time, followed by adding all the time difference
may i know how can i do so?
the code is as followed
function THcheck() {
var a, s, timeDiff, hr = 0;
var hdate, startTime, endTime, totalTime, timeDiff;
var output = "Date StartTime: EndTime: TimeDiff <br>";
var msg = "";
var DStime, DEtime;
var e = document.getElementsByTagName('input');
for (a = 0; e !== a; a++) {
if (e[a].type == "time" && e[a].name == "THStime[]") {
if (e[a].value && e[a].value !== "") {
startTime = e[a].value;
endTime = e[a + 1].value;
hdate = e[a - 1].value
alert(hdate + " " + startTime + " " + endTime);
timeDiff = endTime - startTime;
alert(timeDiff);
hr = parseInt(timeDiff.asHours());
alert(timeDiff);
totalTime += timeDiff;
alert(totalTime);
output += hdate + " " + startTime + " " + endTime + " " + timeDiff + "<br>";
if (hr >= 24) {
msg = "<br> Exceed 24 hrs! ";
}
}
}
}
alert(output + " Total time: " + totalTime + msg);
return true;
}
thanks in advance for your kind assistance and help on this!
I think you need to parse the hours first, converting from string to date and then convert the dates to milliseconds and use the milliseconds for the difference calculation. After this you convert the difference milliseconds into hours.
Here is some sample code which performs these steps:
const dateRegex = /(\d{2}):(\d{2})/;
function diffDatesInHours(d1Str, d2Str) {
const r1 = dateRegex.exec(d1Str);
const r2 = dateRegex.exec(d2Str);
if (!checkDate(r1)) {
console.log("First date format incorrect: " + d1Str);
return null;
}
if (!checkDate(r2)) {
console.log("Second date format incorrect: " + d2Str);
return null;
}
const d1 = createDateFrom(r1);
const d2 = createDateFrom(r2);
const diff = d1.getTime() - d2.getTime();
return Math.abs(diff) / (1000 * 60 * 60);
}
function checkDate(r) {
if (r === null) {
return null;
}
return r.length > 0;
}
function createDateFrom(r) {
let date = new Date();
date.setHours(r[1], r[2]);
return date;
}
console.log(diffDatesInHours("09:30", "21:00"));
console.log(diffDatesInHours("09:30", "21:"));
I'm currently using this function to calculate 2 fields and the results are good but sometimes missing a zero. sample
10:20 + 10:30 current output 0.10
10:20 + 10:30 I want the output to be 00.10
$(function () {
function calculate() {
time1 = $("#start").val().split(':'),
time2 = $("#end").val().split(':');
hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10);
hours = hours2 - hours1,
mins = 0;
if(hours < 0) hours = 24 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
} else {
mins = (mins2 + 60) - mins1;
}
// the result
$("#hours").val(hours + ':' + mins);
}
});
also when there is an invalid character I keep getting a nan message is possible to change this to 00 instead?
Instead of dealing with the strings and each value independently, you can use the javascript Date object to calculate the difference...
function calculate() {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + $('#start').val());
var time2 = new Date('01/01/2017 ' + $('#end').val());
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Set the result adding '0' to the left if needed
$("#hours").val((hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes));
}
Or even better, you can make the function independent of the DOM elements, so you can reuse it...
function calculate(startTime,endTime) {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + startTime);
var time2 = new Date('01/01/2017 ' + endTime);
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Return the response, adding '0' to the left of each field if needed.
return (hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes);
}
// Now you can use the function.
$("#hours").val(calculate($('#start').val(),$('#end').val()));
Add a function
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
and call this function before displaying result
I propose you that :
$(".calculator").on("change",function(){
var isNegative = false;
var hours = "00:00";
var inputStart = $("#start").val();
var inputEnd = $("#end").val();
if(inputStart!="" && inputEnd != ""){
// calculate only if the 2 fields have inputs
// convert to seconds (more convenient)
var seconds1 = stringToSeconds(inputStart);
var seconds2 = stringToSeconds(inputEnd);
var secondsDiff = seconds2 - seconds1;
var milliDiffs = secondsDiff * 1000;
if(milliDiffs < 0){
milliDiffs = milliDiffs *-1;
isNegative = true;
}
// Convert the difference to date
var diff = new Date(milliDiffs);
// convert the date to string
hours = diff.toUTCString();
// extract the time information in the string 00:00:00
var regex = new RegExp(/[0-9]{2}:[0-9]{2}:[0-9]{2}/);
var arr = hours.match(regex);
hours = arr[0];
// Take only hours and minutes and leave the seconds
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
// put minus in front if negative
if(isNegative){
hours = "-"+hours;
}
// Show the result
$("#hours").val(hours);
// Put back the inputs times in case there were somehow wrong
// (it's the same process)
var date1 = new Date(seconds1*1000);
var str1 = date1.toUTCString();
arr = str1.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#start").val(hours);
// idem for time 2
var date2 = new Date(seconds2*1000);
var str2 = date2.toUTCString();
arr = str2.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#end").val(hours);
}
});
function timeElementToString(timeElement){
var output = timeElement.toString();
if(timeElement < 10 && timeElement >=0)
output = "0"+output;
else if(timeElement < 0 && timeElement >=-10)
output = "-0"+Math.abs(output);
return output;
}
function stringToSeconds(input){
var hours = 0;
var arr=input.split(":");
if(arr.length==2){
hours=parseInt(arr[0]);
minutes=parseInt(arr[1]);
if(isNaN(hours)){
hours = 0;
}
if(isNaN(minutes)){
minutes = 0;
}
}
return hours*3600+60*minutes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="start">Start</label><input type="text" id="start" class="calculator"></input><br />
<label for="end">End</label><input type="text" id="end" class="calculator"></input><br />
<label for="hours">Hours</label><input type="text" id="hours" readonly="readonly"></input>
</form>
I am new to JavaScript and I'm getting an error as below.
Uncaught TypeError: time.indexOf is not a function
Gee, I really thought indexOf() really was a function. Here is a snippet of my code:
var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;
document.getElementById("oset").innerHTML = timeD2C(timeofday);
</script>
<script>
function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)
var pos = time.indexOf('.');
var hrs = time.substr(1, pos - 1);
var min = (time.substr(pos, 2)) * 60;
if (hrs > 11) {
hrs = (hrs - 12) + ":" + min + " PM";
} else {
hrs += ":" + min + " AM";
}
return hrs;
}
</script>
Basically indexOf() is a method belongs to string(array object also), But while calling the function you are passing a number, try to cast it to a string and pass it.
document.getElementById("oset").innerHTML = timeD2C(timeofday + "");
var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;
function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)
var pos = time.indexOf('.');
var hrs = time.substr(1, pos - 1);
var min = (time.substr(pos, 2)) * 60;
if (hrs > 11) {
hrs = (hrs - 12) + ":" + min + " PM";
} else {
hrs += ":" + min + " AM";
}
return hrs;
}
alert(timeD2C(timeofday+""));
And it is good to do the string conversion inside your function definition,
function timeD2C(time) {
time = time + "";
var pos = time.indexOf('.');
So that the code flow won't break at times when devs forget to pass a string into this function.
Convert timeofday to string to use indexOf
var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;
console.log(typeof(timeofday)) // for testing will log number
function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)
var pos = time.indexOf('.');
var hrs = time.substr(1, pos - 1);
var min = (time.substr(pos, 2)) * 60;
if (hrs > 11) {
hrs = (hrs - 12) + ":" + min + " PM";
} else {
hrs += ":" + min + " AM";
}
return hrs;
}
// "" for typecasting to string
document.getElementById("oset").innerHTML = timeD2C(""+timeofday);
Test Here
Solution 2
use toString() to convert to string
document.getElementById("oset").innerHTML = timeD2C(timeofday.toString());
jsfiddle with toString()
I was getting e.data.indexOf is not a function error, after debugging it, I found that it was actually a TypeError, which meant, indexOf() being a function is applicable to strings, so I typecasted the data like the following and then used the indexOf() method to make it work
e.data.toString().indexOf('<stringToBeMatchedToPosition>')
Not sure if my answer was accurate to the question, but yes shared my opinion as i faced a similar kind of situation.
I ran across this error recently using a javascript library which changes the parameters of a function based on conditions.
You can test an object to see if it has the function. I would only do this in scenarios where you don't control what is getting passed to you.
if( param.indexOf != undefined ) {
// we have a string or other object that
// happens to have a function named indexOf
}
You can test this in your browser console:
> (3).indexOf == undefined;
true
> "".indexOf == undefined;
false
I'm writing a shortcut JavaScript file to make $date and $time variables. It should work as far as I can tell, but it won't display and Google Chrome's debugger shows a [Uncaught TypeError: Cannot Read 'firstChild' of null]
Here's my code:
function mdy(){
var
h = new Date(),
year = h.getFullYear(),
month = h.getMonth() + 1,
day = h.getDate();
if(month < 10) { month = "0" + month; }
if(day < 10) { month = "0" + month; }
var string = month + "/" + day + "/" + year;
document.getElementById('mdy').firstChild.nodeValue = string;
}
function ymd(){
var
h = new Date(),
year = h.getFullYear(),
month = h.getMonth() + 1,
day = h.getDate();
if(month < 10) { month = "0" + month; }
if(day < 10) { month = "0" + month; }
var string = year + "/" + month + "/" + day;
document.getElementById('ymd').firstChild.nodeValue = string;
}
var $date = {
mdy: '<span id="mdy"> </span>',
ymd: '<span id="ymd"> </span>'
}
/* $time module */
// this comes in two formats, standard and military.
// type $time.standard for standard time and $time.military
// for military time
function tstandard(){
var
h = new Date(),
hours = h.getHours(),
minutes = h.getMinutes();
minutes = ( minutes < 10 ? "0" : "" ) + minutes;
var diem = ( hours < 12 ) ? "am" : "pm";
hours = ( hours > 12 ) ? hours - 12 : hours;
hours = ( hours == 0 ) ? 12 : hours;
var string = hours + ":" + minutes + " " + diem;
document.getElementById("tstandard").firstChild.nodeValue = string;
}
function tmilitary() {
var
h = new Date(),
hours = h.getHours(),
minutes = h.getMinutes();
minutes = ( minutes < 10 ? "0" : "" ) + minutes;
hours = ( hours == 0 ) ? 12 : hours;
if(hours < 10) { hours = "0" + hours }
var string = hours + ":" + minutes;
document.getElementById("tmilitary").firstChild.nodeValue = string;
}
var $time = {
standard: "<span id='tstandard'> </span>",
military: "<span id='tmilitary'> </span>"
}
/*! universal body onload function !*/
window.onload = function(){
mdy(); setInterval('mdy()', 1000);
ymd(); setInterval('ymd()', 1000);
tstandard(); setInterval('tstandard()', 1000);
tmilitary(); setInterval('tmilitary()', 1000);
}
And in my HTML, I'm doing:
<script>document.write($date.mdy + " - " + $time.standard);</script>
You are adding two placeholder elements to the DOM – <span id="ymd"></span> and <span id="tstandard">.
Then, in the window.onload handler, you are trying to update contents of not only these two placeholders but also of two other elements which are not in the DOM (id="ymd" and id="tmilitary"). The document.getElementById('ymd') (and 'tmilitary') call correctly returns undefined because of that fact.
You want to remove the calls to the ymd and tmilitary functions.
window.onload = function(){
mdy();
setInterval(mdy, 1000);
tstandard();
setInterval(tstandard, 1000);
};
I also changed the calls to setInterval to simplify things. Passing references is more efficient and clear.
I think you might want this:
document.getElementById('mdy').innerHTML = string;
or this:
document.getElementById('mdy').nodeValue = string;
instead of this:
document.getElementById('mdy').firstChild.nodeValue = string;
That should take care of the errors. (There's no need to get the firstChild from a getElementById call, it already returns a node by default.)
I have two values that are used for the amount of time it will take to complete a task. How can I add these values together to come up with a total number of hours and minutes, but still have the value account for 60 minutes equalling one hour?
The two values I'd like to get the sum of and the total value are in HH:MM (00:00) format.
Thanks!
Writing your own time and date functions can get complex. Why re-invent the wheel. Take a look at the excellent http://www.datejs.com/ date library. It handles all date and time related tasks and usage is very simple.
Here's something I had laying around. It allows for an infinite number of arguments, so you could have addTime('01:00') or addTime('01:00', '02:00', '03:00', '04:00'), etc. It's three functions long because it also verifies if the times entered are properly formatted, and if not, then it formats them. (E.g. Ensures that minutes is 2 digits long, and if hours is 1 digit long, then pad it with one zero, etc.)
You can play with it here: http://jsfiddle.net/WyxwU/
It's also here:
var totalTime = addTime('12:34', '56:12', '78:45');
document.write(totalTime);
function addTime()
{
if (arguments.length < 2)
{
if (arguments.length == 1 && isFormattedDate(arguments[0])) return arguments[0];
else return false;
}
var time1Split, time2Split, totalHours, totalMinutes;
if (isFormattedDate(arguments[0])) var totalTime = arguments[0];
else return false;
for (var i = 1; i < arguments.length; i++)
{
// Add them up
time1Split = totalTime.split(':');
time2Split = arguments[i].split(':');
totalHours = parseInt(time1Split[0]) + parseInt(time2Split[0]);
totalMinutes = parseInt(time1Split[1]) + parseInt(time2Split[1]);
// If total minutes is more than 59, then convert to hours and minutes
if (totalMinutes > 59)
{
totalHours += Math.floor(totalMinutes / 60);
totalMinutes = totalMinutes % 60;
}
totalTime = totalHours + ':' + padWithZeros(totalMinutes);
}
return totalTime;
}
function isFormattedDate(date)
{
var splitDate = date.split(':');
if (splitDate.length == 2 && (parseInt(splitDate[0]) + '').length <= 2 && (parseInt(splitDate[1]) + '').length <= 2) return true;
else return false;
}
function padWithZeros(number)
{
var lengthOfNumber = (parseInt(number) + '').length;
if (lengthOfNumber == 2) return number;
else if (lengthOfNumber == 1) return '0' + number;
else if (lengthOfNumber == 0) return '00';
else return false;
}
Here is the simple JS code for this,
var a = "2:50";
var b = "2:15";
var splitTimeStr = function(t){
var t = t.split(":");
t[0] = Number(t[0]);
t[1] = Number(t[1]);
return t;
};
var addTime = function(t1, t2){
var t1Hr = splitTimeStr(t1)[0];
var t1Min = splitTimeStr(t1)[1];
var t2Hr = splitTimeStr(t2)[0];
var t2Min = splitTimeStr(t2)[1];
var rHr = t1Hr + t2Hr;
var rMin = t1Min + t2Min;
if (rMin >= 60)
{
rMin = rMin - 60;
rHr = rHr + 1;
}
if (rMin < 10) rMin = "0" + rMin;
if (rHr < 10) rHr = "0" + rHr;
return "" + rHr + ":" + rMin;
};
document.write(addTime(a, b));
you can validate/play this with code here: http://jsfiddle.net/z24v7/
What you have to do is calculate them to a decimal by that I mean.
Strip out the hour/mins multiple that by 60 + to mins
//strip out the hours
l_hour = Number(l_time$.substr(0, l_pos));
//Strip out the mins
l_min = Number(l_time$.substr(l_pos + 1, l_time$.length));
//add the two values divided by 60 mins
l_time_decimal= Number(Math.abs(l_hour)) + Number(Math.abs(l_min)/60);
Do this for each value then deduct the two figures to give you the difference (i.e time taken). All thats left is convert it back from a decimal to a time
l_difference_in_min = l_difference * 60;
l_time_mins = l_difference_in_min%60;
l_time_hours = (l_difference_in_min - l_mins)/60;
Now just format the two to be HH:MM
I would break the problem into sub-tasks that are reusable. You have to concerns here:
Process a time string in "hh:mm" format: Converting this to minutes makes sense because it seems to be the time granularity at which you're operating.
Format a given number of minutes into a time string in "hh:mm" format.
The fact that you're adding two times together is a diversion from the actual two problems above.
Parse a time string into minutes:
function parseMinutes(s) {
var tokens = s.split(":");
return tokens[0] * 60 + parseInt(tokens[1]);
}
Format minutes into a time string:
function formatMinutes(minutes) {
function pad(n) {
return n > 9
? n
: ("0" + n);
}
var hours = Math.floor(minutes / 60),
mins = minutes % 60;
return pad(hours) + ":" + pad(mins);
}
Then your specific problem can be tackled by:
var sum = formatMinutes(parseMinutes(a) + parseMinutes(b));