Javascript onkeyup event only working in Chrome time calculator - javascript

<script>
function numeri_validator(t) {
var patt = /(\d*)\.{1}(\d{0,2})/;
var donepatt = /^(\d*)\.{1}(\d{2})$/;
var str = t.value;
var result;
if (!str.match(donepatt)) {
result = str.match(patt);
if (result != null) {
t.value = t.value.replace(/[^\d]/gi, '');
str = result[1] + '.' + result[2];
t.value = str;
} else {
if (t.value.match(/[^\d]/gi))
t.value = t.value.replace(/[^\d]/gi, '');
}
}
//get the date
var val1 = document.getElementById("cost" + 1).value;
var val2 = document.getElementById("cost" + 2).value;
//Get date
var date = document.getElementById("Label1").innerText;
//format time
var timeIn = val1.replace('.', ':');
var timeOut = val2.replace('.', ':');
//Concat time with date
var timeinDate = date + " " + timeIn;
var timeoutDate = date + " " + timeOut;
//calculate time difference
var nDifference = Math.abs(new Date(timeoutDate) - new Date(timeinDate));
var one_hours = 1000 * 60 * 60;
var hours = (Math.floor(nDifference / one_hours));
var diff = nDifference % one_hours;
var one_min = 1000 * 60;
var diffmin = Math.round(diff / one_min);
document.getElementById("datelabel").innerText = hours + "." + diffmin;
document.getElementById("total").value = hours + "." + diffmin;
This function calculating the difference between the two times is working fine but is working only in Chrome in other browsers is:
document.getElementById("total").value=NaN:NaN
Please help me.

The issue should be because of this part in your code. .innerText.
var date = document.getElementById("Label1").innerText;
.innerText doesn't work in Mozilla. Use .textContent instead
var date = document.getElementById("Label1").textContent;

I solved this problem by changing the date format. Actually this problem with new Date()
The new Date format should be
new Date('2013/10/19 12:00') // not 2013-10-19
Now is working on all browsers
Thanks

Related

Sum Hours:Minutes:Seconds in Java script

how can I sum hours:minutes:seconds in JavaScript.
I mean by
04:32:05
03:14:03
To get
07:46:08
Ive tried
var time1 = "01:00:01";
var time2 = "01:00:10";
var time3 = "01:54:00";
var time4 = "01:30:00";
var time5 = "01:00:00";
var time6 = "01:00:00";
var time7 = "01:00:00";
var hour=0;
var minute=0;
var second=0;
var splitTime1= time1.split(':');
var splitTime2= time2.split(':');
var splitTime3= time3.split(':');
var splitTime4= time4.split(':');
var splitTime5= time5.split(':');
var splitTime6= time6.split(':');
var splitTime7= time7.split(':');
hour = parseInt(splitTime1[0]) + parseInt(splitTime2[0]) + parseInt(splitTime3[0]) + parseInt(splitTime4[0]) + parseInt(splitTime5[0]) + parseInt(splitTime6[0]) + parseInt(splitTime7[0])
minute = parseInt(splitTime1[1]) + parseInt(splitTime2[1]) + parseInt(splitTime3[1]) + parseInt(splitTime4[1]) + parseInt(splitTime5[1]) + parseInt(splitTime6[1]) + parseInt(splitTime7[1])
hour = hour + minute/60;
minute = minute%60;
second = parseInt(splitTime1[2]) + parseInt(splitTime2[2]) + parseInt(splitTime3[2])
+ parseInt(splitTime4[2]) + parseInt(splitTime5[2]) + parseInt(splitTime6[2]) +
parseInt(splitTime7[2])
minute = minute + second/60;
second = second%60;
console.log(hour+ ":" + minute + ":"+ second)
The output I get is 8.4:24.183333333333334:11 instad of 08:24:11
any suggestions?
your making it very complex, you can reduce this by converting into Date objects and then add each date to get the sum of all dates
Understanding Date and Time in JavaScript
The problem with your code is you are including the decimal point
hour = hour + minute/60;
you need to floor it.
hour = hour + Math.floor(minute/60);
Now how to do it without a lot of repetitive code.
function toSeconds(s) {
const parts = s.split(':');
return +parts[0] * 3600 + +parts[1] * 60 + +parts[2];
}
function secondsToHHMMSS(secs) {
return Math.floor(secs / 3600).toString().padStart(2, '0') + ':' +
(Math.floor(secs / 60) % 60).toString().padStart(2, '0') + ':' +
(secs % 60).toString().padStart(2, '0');
}
const timestamps = ["01:00:01", "01:00:10", "01:54:00", "01:30:00", "01:00:00", "01:00:00", "01:00:00"];
const totalSeconds = timestamps.reduce(function(total, ts) {
return total + toSeconds(ts);
}, 0);
const result = secondsToHHMMSS(totalSeconds);
console.log(result);
If you want to sum of times then you should try this
var addTime = function (time1, time2) {
// convert to ms
var dateObject1 = new Date(time1).valueOf();
var dateObject2 = new Date(time2).valueOf();
return dateObject1 + dateObject2;
}
var time1 = new Date().setHours(4, 32, 5, 0);
var time2 = new Date().setHours(3, 14, 3, 0);
var sum = new Date(addTime(time1, time2));
var getFormatedTime = function (time) {
return time.getHours()+':'+time.getMinutes()+':'+time.getSeconds()
}
console.log(getFormatedTime(sum))
The first thing you should look into is using an Array, since you have a number of objects of the same kind.
You should ideally have something like,
const times = ["04:32:05", "03:14:03", ...]
Once you have that, this problem reduces to a classic use-case for the reduce function.
The reduce function operates on an array and accumulates the value of the operation every step to yield one value at the end.
Here's an example solution for your problem
const times = ["04:32:05", "03:14:03"]
//const times = ["01:00:01", "01:00:10","01:54:00","01:30:00"]
let finalSum = times.reduce((sum, curr) => {
//Obtain the current timestamp as an array of numbers
//[HRS, MINS, SECS]
let currTimeStamp = curr.split(":").map(token => parseInt(token));
//Add the current seconds to the total seconds so far
sum[2] += currTimeStamp[2];
//See how many minutes you got leftover as a result of that addition
const leftOverMins = Math.floor(sum[2] / 60);
//Mod by 60, to keep the seconds under 60
sum[2] %= 60;
//Add the leftover minutes to the sum operation for minutes
sum[1] += (currTimeStamp[1] + leftOverMins);
//Similar procedure as above
const leftOverHours = Math.floor(sum[1] / 60);
sum[1] %= 60;
sum[0] += (currTimeStamp[0] + leftOverHours);
sum[0] %= 24;
return sum
}, [0, 0, 0])
console.log(finalSum.join(":"))
Hello hope this answer will help you, I recommand to replace your bottom part (where you calculate) I do pretty much the same thing, but in the good order and with round to avoid decimals problems
var time1 = "01:00:01";
var time2 = "01:00:10";
var time3 = "01:54:00";
var time4 = "01:30:00";
var time5 = "01:00:00";
var time6 = "01:00:00";
var time7 = "01:00:00";
var hour=0;
var minute=0;
var second=0;
var splitTime1= time1.split(':');
var splitTime2= time2.split(':');
var splitTime3= time3.split(':');
var splitTime4= time4.split(':');
var splitTime5= time5.split(':');
var splitTime6= time6.split(':');
var splitTime7= time7.split(':');
var allTimes = [splitTime1, splitTime2, splitTime3, splitTime4, splitTime5, splitTime6, splitTime7]
allTimes.forEach(element => {
hour += parseInt(element[0])
minute += parseInt(element[1])
second += parseInt(element[2])
})
minute += Math.round(second / 60);
second = second % 60;
hour += Math.round(minute / 60);
minute = minute % 60
console.log(hour+ ":" + minute + ":"+ second)

Generate a random string on employee custom field in ERPNext

I have a custom employee field called Misconduct Case Number that’s supposed to be extracted and used elsewhere outside ERPNext. The random string should be in the format [8 Alfanumeric charactors] [Date & Time] [Constant Organization Number] eg DX0FBN78 04200645 PTD0010045
For some reason, I am not able to generate the random string using the following custom script and there are no errors in the console.
frappe.ui.form.on('Employee', {
validate: function (frm) {
randString(frm);
}
});
var randString = function (frm) {
var s = "";
var x = "";
var today = new Date();
var date = String(today.getFullYear()).substring(2, 4) + '' + (today.getMonth() + 1);
var time = today.getHours() + "" + today.getMinutes();
var dateTime = date + time;
var compNumber = " STR18001749";
while (s.length < x && x > 0) {
var r = Math.random();
s += (r < 0.1 ? Math.floor(r * 100) : String.fromCharCode(Math.floor(r * 26) + (r > 0.5 ? 97 : 65)));
}
let my_generated_string = s.toUpperCase() + ' ' + dateTime + compNumber;
frm.doc.misconduct = my_generated_string ;
refresh_field('misconduct');
};
Well, for one, x is not a number, doesn't change, and never satisfies x > 0.
Not sure what kind of JS is supported in ERPNext, but this should work:
var pool = "abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ0123456789";
var compNumber = " STR18001749";
var randString = function(frm) {
var s = "";
var today = new Date();
var date = String(today.getFullYear()).substring(2, 4) + '' + (today.getMonth() + 1);
var time = today.getHours() + "" + today.getMinutes();
var dateTime = date + time;
while (s.length < 8) {
var i = Math.floor(Math.random() * pool.length);
s += pool[i];
}
frm.doc.misconduct = s.toUpperCase() + ' ' + dateTime + compNumber;
// refresh_field('misconduct'); // commented out so the snippet runs
};
x = {doc: {}};
randString(x);
console.log(x);

UTC live clock, not working with negative timezone

In my application, I need to create live clock according to different timezones which are stored into database.
I have almost succeeded it.
But now I'm facing negative time in clock, and I'm out of ideas to figure out a solution.
I'm getting UTC time with the help of new Date() and calculating time with provided timezone from database.
Case 1: 0:31 (UTC time) + 5:30 (timezone) = '06:01'
Case 2: 06:31 (UTC time) - 6:30 (timezone) = '00:01'
Case 3: 5:0 (UTC time) - 7:0 (timezone) = '-02:00'
Case 1 and 2 is working properly but I'm getting negative value in 3rd case which is wrong.
I have tried to add comments in code to have better understanding of what I'm doing here. I hope it helps.
Any help will be highly appreciated.
function runClock() {
setInterval(function() {
//debugger
var time = new Date();
// take timezone from HTML element
// ex: +:5:30
var getTimezone = "-:7:0" //$("#timeZone").text();
// split into array to get oparator (Positive and Negative Timezone)
var oparator = getTimezone.split(":")[0];
var timezone = getTimezone.split(":")[1] + ":" + getTimezone.split(":")[2];
// get UTC hours
var hours = 5 //time.getUTCHours();
var minutes = 0 //time.getUTCMinutes();
var UTCTIME = timeStringToFloat(hours + ":" + minutes);
var TIMEZONEOFFSETTIME = timeStringToFloat(timezone);
var finalTime = "";
// Convert time folloed by Colon into decimals
// ex: 1:45 = 1.75
function timeStringToFloat(time) {
var hoursMinutes = time.split(/[.:]/);
var hh = parseInt(hoursMinutes[0], 10);
var mm = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
return hh + mm / 60;
}
// Convert time folloed by float into Colon
// ex: 1.75 = 1:45
function floatToTime(FT) {
var splittedTime = FT.toString().split(".");
var hh = splittedTime[0];
var mm = "";
if (splittedTime[1]) {
mm = Math.round((splittedTime[1] / 100) * 60);
} else {
mm = "0";
}
finalTime = hh + ":" + ((mm < 10) ? ("0" + mm) : mm);
}
// Calculate time (UTC + or - Timezone)
// Ex: 00:15 (UTC) + 5:30 = 5:45
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
}
}
// Parse Seconds
function seconds() {
var j = "";
if (time.getUTCSeconds() < 10) {
j = "0" + time.getUTCSeconds();
} else {
j = time.getUTCSeconds()
}
return j;
}
CalcTime(UTCTIME, TIMEZONEOFFSETTIME);
$("#clockTime").text(finalTime + ":" + seconds());
}, 1000);
}
runClock();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b id="clockTime"></b>
You should just be "looping back" to 23:59 when you go negative. You can just add something to check if it goes negative then just re-add the missing time:
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME;
// Offset any negative times;
if (FT < 0) {
FT += 24;
}
FT = FT.toFixed(2);
floatToTime(FT);
}
}
But ideally you really don't want to be handling these kinds of Timezone issues as other libraries are already handling it, i.e. moment.js
function runClock() {
setInterval(function() {
//debugger
var time = new Date();
// take timezone from HTML element
// ex: +:5:30
var getTimezone = "-:7:0" //$("#timeZone").text();
// split into array to get oparator (Positive and Negative Timezone)
var oparator = getTimezone.split(":")[0];
var timezone = getTimezone.split(":")[1] + ":" + getTimezone.split(":")[2];
// get UTC hours
var hours = 5 //time.getUTCHours();
var minutes = 0 //time.getUTCMinutes();
var UTCTIME = timeStringToFloat(hours + ":" + minutes);
var TIMEZONEOFFSETTIME = timeStringToFloat(timezone);
var finalTime = "";
// Convert time folloed by Colon into decimals
// ex: 1:45 = 1.75
function timeStringToFloat(time) {
var hoursMinutes = time.split(/[.:]/);
var hh = parseInt(hoursMinutes[0], 10);
var mm = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
return hh + mm / 60;
}
// Convert time folloed by float into Colon
// ex: 1.75 = 1:45
function floatToTime(FT) {
var splittedTime = FT.toString().split(".");
var hh = splittedTime[0];
var mm = "";
if (splittedTime[1]) {
mm = Math.round((splittedTime[1] / 100) * 60);
} else {
mm = "0";
}
finalTime = hh + ":" + ((mm < 10) ? ("0" + mm) : mm);
}
// Calculate time (UTC + or - Timezone)
// Ex: 00:15 (UTC) + 5:30 = 5:45
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME;
// Offset any negative times;
if (FT < 0) {
FT += 24;
}
FT = FT.toFixed(2);
floatToTime(FT);
}
}
// Parse Seconds
function seconds() {
var j = "";
if (time.getUTCSeconds() < 10) {
j = "0" + time.getUTCSeconds();
} else {
j = time.getUTCSeconds()
}
return j;
}
CalcTime(UTCTIME, TIMEZONEOFFSETTIME);
$("#clockTime").text(finalTime + ":" + seconds());
}, 1000);
}
runClock();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b id="clockTime"></b>
You want to recover/display the time for a given timezone offset? Unless you like doing this for a hobby, stay away from string methods and use the date functions, no?
var offsetMS = -5.5 * 3600000
var myDate = new Date()
var dateWithOffset = new Date( myDate.getTime() + offsetMS )
var formatted = dateWithOffset.toLocaleString("en-GB",{timeZone:"UTC",hour:"numeric",minute:"numeric"})
console.log(formatted)
Even manipulating timezone offset directly is to be avoided. If you can, use toLocaleString with a real timezone name, then issues like daylight saving will be handled for you. Modern browsers support all iana timezones, so let them do the work.
Add 24 to your FT value and take division remain of 24:
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME + 24;
FT = FT % 24;
}
FT = FT.toFixed(2);
floatToTime(FT);
}
Working sample: https://codepen.io/anon/pen/VqQqoo
If you do not want to use a library like moment.js that comes with time zone handling and simply need to add/subtract hours from a given date, how about converting them to a common time unit and operating on that?
const timezoneString = '-:12:30';
const parts = timezoneString.split(':');
const timezone = (parts[0] === '-' ? -1 : 1) * (parseInt(parts[1]) + (parseInt(parts[2]) / 60.0));
const timeZoneMillis = timezone * 3600 * 1000;
const now = new Date();
const inZone = new Date(now.getTime() + timeZoneMillis);
console.log(now, inZone);
Something like this would convert them to a millisecond timestamp and subtract that many hours and convert it back to a date.

How to sum of hours (hh:mm:ss) in jquery? [duplicate]

This question already has answers here:
Add multiple DateTime Duration strings together using JavaScript to get total duration
(4 answers)
Closed 6 years ago.
How to sum of hours (hh:mm:ss) in jquery?
For Ex. :
I need to sum of 40:50:40 hours and 04:12:30 hours in jQuery.
And result should be
45:03:10
You can try following javascript code...
var prodhrd = "40:50:40";
var conprodArr = "04:12:30";
prodhrdArr = prodhrd.split(":");
conprodArr = conprod.split(":");
var hh1 = parseInt(prodhrdArr[0]) + parseInt(conprodArr[0]);
var mm1 = parseInt(prodhrdArr[1]) + parseInt(conprodArr[1]);
var ss1 = parseInt(prodhrdArr[2]) + parseInt(conprodArr[2]);
if (ss1 > 59) {
var ss2 = ss1 % 60;
var ssx = ss1 / 60;
var ss3 = parseInt(ssx);//add into min
var mm1 = parseInt(mm1) + parseInt(ss3);
var ss1 = ss2;
}
if (mm1 > 59) {
var mm2 = mm1 % 60;
var mmx = mm1 / 60;
var mm3 = parseInt(mmx);//add into hour
var hh1 = parseInt(hh1) + parseInt(mm3);
var mm1 = mm2;
}
var finaladd = hh1 + ':' + mm1 + ':' + ss1;
alert(finaladd);

Convert integers to time and add

I have requirement to converting integer value to time format using javascript.
My requirement is that the result should be in time format.
Example 08:55 and 09:55
If I add these two as numbers then I will get 18.10 but I need 18:50
Try this: (My solution assumes the sum of times is not more than 24 hours)
function pad(str) {
return ("00"+str).slice(-2);
}
var str1 = "08:55";
var str2 = "09:55";
var token1 = str1.split(":");
var token2 = str2.split(":");
var result = token1[0] * 60 + + token1[1] + + token2[0] * 60 + + token2[1];
var newTime = pad(Math.floor(result/60)) + ":" + pad(result % 60);
console.log(newTime);

Categories

Resources