Javascript not able to evaluate expression - javascript

I m trying to calculate a day diff in Javascript to apply some value. The first expression
if subs_start
is working fine, but the second one
subs_end
is not working, same goes with
subs_mid
Code:
var subs_start = 0;
var subs_mid = 0;
var subs_end = 0;
var dayDiff = (end_year*365 + end_mon * 30 + end_day)
- (start_year*365 + start_mon* 30 + start_day);
var oneDay=1000*60*60*24;
var oneHour = 1000*60*60;
var timeDiff = endDate.getTime() - startDate.getTime();
var hourDiff = timeDiff/oneHour;
var start_rem_hour = 24 - start_hour*1;
$.each(subsistence, function(id,subs){
if(subs.start <= start_rem_hour && start_rem_hour < subs.end ){
subs_start = subs.rate;
}
alert('T' + end_hour);
if(subs.start <= end_hour && end_hour < subs.end ){
subs_end = subs.rate;
alert ('e ' + subs_end);
}
if(dayDiff > 2){
if(subs.start >= 10){
subs_mid = subs.rate * (dayDiff - 2);
alert ('m ' + subs_mid);
}
}
});
var subs_allow = subs_start*1 + subs_mid*1 + subs_end*1 ;

I m finally able to find the answer. I need to multiple start_rem_hour and end_hour with 1 to convert into int. It seems js is taking them as string and when i multiply with 1 it gets into integer scope.

Not sure what is being asked for.
For DateTime calculations in javascript I would recommend Datejs library:
http://www.datejs.com/

Related

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);

Function works incorrectly when called by another function

First post here. I am trying to create an Easter Calculator for a school project. The function pasCalc(E) works great when called on its own on the browser console. However, when I type a year in my html form, all the dates are off.
Sorry if this sounds like a newb question, but I can't figure out what's wrong... Any help will be greatly appreciated, thank you for your time! :)
function start() {
document.getElementById("orthodox").innerHTML = "Ορθόδοξο πάσχα:";
//var E = document.getElementById("inputfield").value;
//console.log(E);
var pasxa = pasCalc(document.getElementById("inputfield").value)
console.log(pasxa);
//console.log(pasxa[0] + " " + pasxa[1]);
document.getElementById("orthodox").innerHTML += " " + pasxa;
}
function pasCalc(E) {
//var E = 2018;
var a = E % 19;
var T = (8 + 11 * a) % 30;
var month = "Mach";
var K = Math.floor((E / 100) - (E / 400) - 2);
var iPanArx = 21 + (53 - T) % 30;
if (iPanArx > 31) {
var iPanArxM = iPanArx - 31;
month = "April";
} else {
var iPanArxM = iPanArx;
}
var iPanTel = iPanArxM + K;
var Y = (E + Math.floor(E / 4) + iPanArx) % 7;
var iPas = iPanTel + (7 - Y);
if (iPas > 30 && month == "April") {
month = "May";
var iPas = iPas - 30;
} else if (iPas > 31 && month == "Marchυ") {
month = "April";
var iPas = iPas - 31;
}
console.log(iPas + " " + month + " " + E);
var arr = [];
arr.push(iPas);
arr.push(month);
return arr;
}
<div class="container align-center">
<h1>Easter Calculator</h1>
<input id="inputfield" type="text" placeholder="Enter a Year...">
<button class="btn btn-primary" onclick="start();">Submit</button>
<h5 id="orthodox">Orthodox Easter:</h5>
<h5>Catholic Easter:</h5>
</div>
Form fields, by default, are strings. In order for Javascript to know it's an integer so that it works with numeric calculations like the year component of a date, wrap it in a call to parseInt()
var pasxa = pasCalc(parseInt(document.getElementById("inputfield").value))

Finding difference between two dates code not working in Firefox (version 40.0.3)

Recently moved our system from Chrome to Firefox and all code has worked fine except this one:
(I am fairly new to coding so I apologies if code looks dreadful but I had to convert from EU dates to US date so I could parse them to get a time difference.)
var start = Browser.getValue(getElement("mystarttime"));
var eu_date1 = start;
var parts = eu_date1.split('.');
var us_date1 = parts[1]+'-'+parts[0]+'-'+parts[2];
var end = Browser.getValue(getElement("myendtime"));
var eu_date2 = end;
var parts = eu_date2.split('.');
var us_date2 = parts[1]+'-'+parts[0]+'-'+parts[2];
if (start && end){
var diff = Date.parse(us_date2) - Date.parse(us_date1);
var timediff = msToTime(diff); /* Call function 1 */
Browser.setValue(getElement("totaltimeholder"), timediff);
}
else if (start && !end){
var end = new Date();
var diff = Date.parse(end) - Date.parse(us_date1);
var timediff = msToTime(diff);
Browser.setValue(getElement("totaltimeholder"), timediff);
}
It calls this function:
function msToTime(duration) { /* Call function 1 */
var d, h, m, s;
s = Math.floor(duration / 1000);
m = Math.floor(s / 60);
s = s % 60;
h = Math.floor(m / 60);
m = m % 60;
d = Math.floor(h / 24);
h = h % 24;
d = (d < 10) ? "0" + d : d;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
return d + ":" + h + ":" + m;
}
It return NaN:NaN:NaN. Have looked on this site and cannot find information on what could have gone wrong. This works perfect in IE also.
Your msToTime() function works fine in Firefox, too. That having said, you must be providing a wrong value into that function which is not a number.
The problem must lay in your code above. Unless you show us what start and end value is, it's hard to figure out where the real problem is.
Just start debugging with console.log(diff) and look what the value is. And then go up and check which value causes the problem.

How to work out time difference between two times on a 24 hour clock

I have a problem with some code I have been producing in JavaScript. I want to calculate the difference between two times on a 24 hour clock. The data comes from two input time fields:
<input type="time" id="start" />
<input type="time" id="end" />
Because of this the times come in a string 00:00, which doesn't help for number calculations.
The way I worked it out was to minus the start from the end. This works perfectly if the the end time is greater, however if the end time is past 11:00 (00:00), I end up with a negative number. I have tried adding 24 to the result if the end is lower than the start but I still get a negative number. This may seem like a dumb question but I was never that good at maths.
var numHours;
if(time_end < time_start){
numHours = parseInt(t_e.substring(0,2)) - parseInt(t_s.substring(0,2)) + 24;
}else{
numHours = parseInt(t_e.substring(0,2)) - parseInt(t_s.substring(0,2));
}
There is probably (definitely) a better way of doing this but how can I get this to work. Also could I calculate the minutes as well to get more accurate time difference.
The solutions provided aren't accounting for the day boundary effectively. And all of this assumes the difference is less than 24 hours. Meaning that we have an upper boundary on the difference between start and end of 23 hours and 59 minutes, otherwise we are confused by the result. But remember that as described a real use case is that an event starts at 11pm and ends at 1am (from 23:00 to 1:00) and the difference is 2 hours NOT 22 hours.
function calculateTime(e) {
var startTime = $('#start').val();
var endTime = $('#end').val();
var startTimeArray = startTime.split(":");
var startInputHrs = parseInt(startTimeArray[0]);
var startInputMins = parseInt(startTimeArray[1]);
var endTimeArray = endTime.split(":");
var endInputHrs = parseInt(endTimeArray[0]);
var endInputMins = parseInt(endTimeArray[1]);
var startMin = startInputHrs*60 + startInputMins;
var endMin = endInputHrs*60 + endInputMins;
var result;
if (endMin < startMin) {
var minutesPerDay = 24*60;
result = minutesPerDay - startMin; // Minutes till midnight
result += endMin; // Minutes in the next day
} else {
result = endMin - startMin;
}
var minutesElapsed = result % 60;
var hoursElapsed = (result - minutesElapsed) / 60;
alert ( "Elapsed Time : " + hoursElapsed + ":" + (minutesElapsed < 10 ?
'0'+minutesElapsed : minutesElapsed) ) ;
}
And I didn't check, but I believe you could just do this, but I'm not checking it :
var result = endMin - startMin;
if (result < 0 ) result = (24*60) + result;
A simple solution that might work best for this limited use-case is to convert both times into total minutes since the start of the day, and then subtract.
Pseudocode:
startMin = startInputHrs * 60 + startInputMin
endMin = endInputHrs * 60 + endInputMin
timeDifference = endMin - startMin
It's up to you how you want to handle a negative result. Maybe give the user an error message, and tell them that the start time has to come before the end time?
I'm a beginner, and some whiz is probably going to come up with an answer in like 2 lines :), but here it is.....this works. input is a string in the form of "1:20pm-2:30am".
function CountingMinutesI(str) {
split = str.split('-')
startTime = split[0]
endTime = split[1]
// for end time
if (endTime === '12:00am') { endInMinutes = 0}
else if (endTime.charAt(endTime.length-2) === 'a') {
if (endTime.substr(0, 2) === '12') {
endInMinutes = parseInt(endTime.split(':')[1].replace(/[a-z]/gi, ''))
}
else {
endHours = endTime.split(':')[0]
endMins = endTime.split(':')[1].replace(/[a-z]/gi, '')
endInMinutes = (parseInt(endHours)*60) + parseInt(endMins)
}
}
else if (endTime === '12:00pm') {endInMinutes = 720}
else {
endHours = endTime.split(':')[0]
endMins = endTime.split(':')[1].replace(/[a-z]/gi, '')
endInMinutes = (parseInt(endHours)*60 + 720) + parseInt(endMins)
}
// for start time
if (startTime === '12:00am') { startInMinutes = 0}
else if (startTime.charAt(startTime.length-2) === 'a') {
if (startTime.substr(0, 2) === '12') {
startInMinutes = parseInt(startTime.split(':')[1].replace(/[a-z]/gi, ''))
}
else {
startHours = startTime.split(':')[0]
startMins = startTime.split(':')[1].replace(/[a-z]/gi, '')
startInMinutes = (parseInt(startHours)*60) + parseInt(startMins)
}
}
else if (startTime.substr(0,2) === '12') {startInMinutes = 720 + parseInt(startTime.split(':')[1].replace(/[a-z]/gi, ''))}
else {
startHours = startTime.split(':')[0]
startMins = startTime.split(':')[1].replace(/[a-z]/gi, '')
startInMinutes = (parseInt(startHours)*60 + 720) + parseInt(startMins)
}
if (endInMinutes > startInMinutes) {output = endInMinutes - startInMinutes}
else {output = 1440 - (startInMinutes - endInMinutes)}
return output
}

convert time string format

I want to convert time data to the format HH:mm:ss in JavaScript.
I've got a problem in my code (see comments inside the code):
function parseTime(timeString){
var timeString = timeString.toLowerCase();
timeString = $.trim(timeString);
var regEx = /^([0-9]|1[0-9]|2[0-3])$/;
var regEx2 = /^([0-9]|1[0-9]|2[0-3])\.?([0-5][0-9])$/;
var regEx3 = /^([0-9]|1[0-2])(a|p|am|pm)$/;
var regEx4 = /^([1-9]|10|11|12)\.?([0-5][0-9])(a|p|am|pm)$/;
if(regEx.test(timeString)){
var hours = timeString;
if(hours.length == 1){
hours = '0' + hours;
}
return hours + ':00:00';
}
else if(regEx2.test(timeString)){
var hoursEndIndex, minutesStartIndex;
if(timeString.indexOf('.')){
hoursEndIndex = timeString.indexOf('.');
minutesStartIndex = timeString.indexOf('.') + 1;
}else if(timeString.length == 3){//Problem here timeString.length returns 3 but the code below isn't executed?
hoursEndIndex = 1;
minutesStartIndex = 1;
}else if(timeString.length == 4){//Same thing here?
hoursEndIndex = 2;
minutesStartIndex = 2;
return timeString.length;
}
var hours = timeString.substring(0, hoursEndIndex);
if(hours.length == 1){
hours = '0' + hours;
}
var minutes = timeString.substr(minutesStartIndex, 2);
return hours + ':' + minutes + ':00';
}
I think you are using indexOf incorrectly here:
if(timeString.indexOf('.')){
From the documentation:
Returns the first index at which a given element can be found in the array, or -1 if it is not present.
Probably you mean this:
if(timeString.indexOf('.') > -1) {
With your code the expression in the first if statement will be true even if the string does not contain a dot. This means that the else if statement will never be executed.
I want to convert a almost any kind of time format to the format HH:mm:ss in javacript
Check this out: http://www.datejs.com/
There's no reason to re-invent the wheel.
However, if you are required to implement this yourself, then I believe Mark's solution will help
You're using else if, which requires that all preceding conditional blocks equate to false.
Try this:
if(timeString.indexOf('.')){
hoursEndIndex = timeString.indexOf('.');
minutesStartIndex = timeString.indexOf('.') + 1;
}
if(timeString.length == 3){
hoursEndIndex = 1;
minutesStartIndex = 1;
} else if(timeString.length == 4){
hoursEndIndex = 2;
minutesStartIndex = 2;
return timeString.length;
}
Perhaps you should use captured groups instead of parsing the string again:
var groups = regEx2.exec(timeString);
if(groups){
var hours = groups[0];
if(hours.length == 1){
hours = '0' + hours;
}
var minutes = groups[1];
return hours + ":" + minutes + ":00";
}

Categories

Resources