Function works incorrectly when called by another function - javascript

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

Related

using javascript in html to display current date

I have this script which display Gregorian-Hijri date:
var fixd = document.getElementById('date');
function isGregLeapYear(year) {
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
function gregToFixed(year, month, day) {
var a = Math.floor((year - 1) / 4);
var b = Math.floor((year - 1) / 100);
var c = Math.floor((year - 1) / 400);
var d = Math.floor((367 * month - 362) / 12);
if (month <= 2)
e = 0;
else if (month > 2 && isGregLeapYear(year))
e = -1;
else
e = -2;
return 1 - 1 + 365 * (year - 1) + a - b + c + d + e + day;
}
function Hijri(year, month, day) {
this.year = year;
this.month = month;
this.day = day;
this.toFixed = hijriToFixed;
this.toString = hijriToString;
}
function hijriToFixed() {
return this.day + Math.ceil(29.5 * (this.month - 1)) + (this.year - 1) * 354 +
Math.floor((3 + 11 * this.year) / 30) + 227015 - 1;
}
function hijriToString() {
var months = new Array("محرم", "صفر", "ربيع الأول", "ربيع الثانى", "جمادى الأولى", "جمادى الثانية", "رجب", "شعبان", "رمضان", "شوال", "ذو القعدة", "ذو الحجة");
return this.day + " " + months[this.month - 1] + " " + this.year;
}
function fixedToHijri(f) {
var i = new Hijri(1100, 1, 1);
i.year = Math.floor((30 * (f - 227015) + 10646) / 10631);
var i2 = new Hijri(i.year, 1, 1);
var m = Math.ceil((f - 29 - i2.toFixed()) / 29.5) + 1;
i.month = Math.min(m, 12);
i2.year = i.year;
i2.month = i.month;
i2.day = 1;
i.day = f - i2.toFixed() + 1;
return i;
}
var tod = new Date();
var weekday = new Array("الأحد", "الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت");
var monthname = new Array("يناير", "فبراير", "مارس", "ابريل", "ماي", "جوان", "جويلية", "أوت", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر");
var y = tod.getFullYear();
var m = tod.getMonth();
var d = tod.getDate();
var dow = tod.getDay();
document.write(weekday[dow] + " " + d + " " + monthname[m] + " " + y);
m++;
fixd = gregToFixed(y, m, d);
var h = new Hijri(1421, 11, 28);
h = fixedToHijri(fixd);
document.write(" / " + h.toString() + " ");
<div>
<ul>
<li id="date"></li>
</ul>
</div>
I want to use it in <li> tag
and if it is possible to display the date in two different positions at the same time at the same page
actually I am not familiar with java script so I don't know how to modify this script and then call it by id or whatever in html tag
any help please
This is really an extended comment.
The code can be considerably reduced by using the ca option with either toLocaleString or Intl.DateTimeFormat to set the calendar for formatted dates. It can also be used to set the language, e.g.
let d = new Date();
let options = {
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long'
};
console.log(
'Gregorian English: ' + d.toLocaleString('en-u-ca-gergory', options) + '\n' +
'Hijri English : ' + d.toLocaleString('en-u-ca-islamic', options) + '\n' +
'Hijri Arabic : ' + d.toLocaleString('ar-u-ca-islamic', options)
);
You can also use the formatToParts method to get the various parts and order or format them any way you wish.
You can set something like an attribute to any element that needs the date and then assign the innerHTML of that element.
This is all your code except I moved the 'loose' parts into a function that returns the finished date. Then this line
document.querySelectorAll('[display-date]')
.forEach(el => el.innerHTML = getTheDate())
says find all elements with the attribute display-date and insert the results of the date function in them
window.addEventListener('load', () => {
document.querySelectorAll('[display-date]').forEach(el => el.innerHTML = getTheDate())
})
function isGregLeapYear(year) {
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
function gregToFixed(year, month, day) {
var a = Math.floor((year - 1) / 4);
var b = Math.floor((year - 1) / 100);
var c = Math.floor((year - 1) / 400);
var d = Math.floor((367 * month - 362) / 12);
if (month <= 2)
e = 0;
else if (month > 2 && isGregLeapYear(year))
e = -1;
else
e = -2;
return 1 - 1 + 365 * (year - 1) + a - b + c + d + e + day;
}
function Hijri(year, month, day) {
this.year = year;
this.month = month;
this.day = day;
this.toFixed = hijriToFixed;
this.toString = hijriToString;
}
function hijriToFixed() {
return this.day + Math.ceil(29.5 * (this.month - 1)) + (this.year - 1) * 354 +
Math.floor((3 + 11 * this.year) / 30) + 227015 - 1;
}
function hijriToString() {
var months = new Array("محرم", "صفر", "ربيع الأول", "ربيع الثانى", "جمادى الأولى", "جمادى الثانية", "رجب", "شعبان", "رمضان", "شوال", "ذو القعدة", "ذو الحجة");
return this.day + " " + months[this.month - 1] + " " + this.year;
}
function fixedToHijri(f) {
var i = new Hijri(1100, 1, 1);
i.year = Math.floor((30 * (f - 227015) + 10646) / 10631);
var i2 = new Hijri(i.year, 1, 1);
var m = Math.ceil((f - 29 - i2.toFixed()) / 29.5) + 1;
i.month = Math.min(m, 12);
i2.year = i.year;
i2.month = i.month;
i2.day = 1;
i.day = f - i2.toFixed() + 1;
return i;
}
function getTheDate() {
var tod = new Date();
var weekday = new Array("الأحد", "الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت");
var monthname = new Array("يناير", "فبراير", "مارس", "ابريل", "ماي", "جوان", "جويلية", "أوت", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر");
var y = tod.getFullYear();
var m = tod.getMonth();
var d = tod.getDate();
var dow = tod.getDay();
let d1 = (weekday[dow] + " " + d + " " + monthname[m] + " " + y);
m++;
fixd = gregToFixed(y, m, d);
var h = new Hijri(1421, 11, 28);
h = fixedToHijri(fixd);
let d2 = " / " + h.toString() + " ";
return d1 + d2;
}
<div>
<ul>
<li display-date class="date"></li>
</ul>
</div>
<h3 display-date></h3>
<p>Todays date is <span display-date></span></p>

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

javascript Date Object how long ago

I'm trying to show how long ago a video was uploaded, i cant seem to get the hours and minutes Date Object Methods to work in this script. I'm working of a script called YouMax 2.0 and i have been editing the function getDateDiff, i have come up with this edit of the function. Thank you for any help on this.
function getDateDiff(timestamp) {
if (null === timestamp || timestamp === "" || timestamp === "undefined") return "?";
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var d1 = new Date();
var d1Y = d1.getFullYear();
var d2Y = parseInt(splitDate[0], 10);
var d1M = d1.getMonth() + 1;
var d2M = parseInt(splitDate[1], 10);
var d1D = d1.getDate();
var d2D = parseInt(splitDate[2], 10);
var d1H = d1.getHours();
var d2H = parseInt(splitTime[0], 10);
var d1T = d1.getMinutes();
var d2T = parseInt(splitTime[1], 10);
var diffInMinutes = (d1T + 59 * d1H + 23) - (d2T + 59 * d2H + 23);
if (diffInMinutes <= 1) return "1 Minute";
else if (diffInMinutes <= 59) return diffInMinutes + " Minutes";
var diffInHours = (d1H + 23 * d1M) - (d2H + 23 * d1M);
if (diffInHours <= 1) return "1 Hour";
else if (diffInHours < 23) return diffInHours + " Hours";
var diffInDays = (d1D + 30 * d1M + 12 * d1Y) - (d2D + 30 * d2M + 12 * d2Y);
if (diffInDays < 7) return diffInDays + " days";
else if (diffInDays > 7 && diffInDays < 14) return "1 week";
else if (diffInDays >= 14 && diffInDays < 30) return Math.floor(diffInDays / 7) + " weeks";
var diffInMonths = (d1M + 12 * d1Y) - (d2M + 12 * d2Y);
if (diffInMonths <= 1) return "1 month";
else if (diffInMonths < 12) return diffInMonths + " months";
var diffInYears = Math.floor(diffInMonths / 12);
if (diffInYears <= 1) return "1 year";
else if (diffInYears < 12) return diffInYears + " years";
}
my new function only returns minutes and other and wont update to change of day
I assume you are fetching the timestamp from a mysql database. This was also answered here. The top answer is in php but it is not really different from Javascript. I do suggest using php for this however.
you can see that your splitting was not correct...
this is working fine..
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var splitTime1 = ((splitTime[2].toString().split('Z'))[0]).split('.');
splitDate[0] = Year;
splitDate[1] = Month;
splitDate[2] = Day;
splitTime[0] = Hours;
splitTime[1] = Minutes;
splitTime1[0] = Seconds;
splitTime1[1] = MilliSeconds;
you can now perform what ever you want to..

Javascript not able to evaluate expression

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/

Javascript Relative Time - Display difference in Years & Months

Have been fighting this for too many days. I am trying to display the difference of a date (x) and now as follows:
If the diff is exactly a year or years - just display the year diff
If the diff is years and months (1 year, 5 months) display it like that
If the diff is months (no years), display the months diff
If it's days, display the days.
Hope that's clear - I'm very tired.
Here is my code (the commented lines are what I can't get to work):
function RelativeTime(x){
var plural = '';
var mins = 60, hour = mins * 60; day = hour * 24,
week = day * 7, month = week * 4, year = day * 365;
if (x >= year){ x = (x / year)|0; dformat="year"; }
//else
//if ((x >= year)&& (x >= month)) { x = (x / year), (x / month)|0 ; dformat="year" , "month"; }
else if (x >= month) { x = (x / month)|0; dformat="month"; }
else if (x >= day*4) { x = (x / day)|0; dformat="day"; }
else if (x >= hour) { x = (x / hour)|0; dformat="hr"; }
else if (x >= mins) { x = (x / mins)|0; dformat="min"; }
else { x |= 0; dformat="sec"; }
if (x > 1) plural = 's';
if (x < 0) x = 0;
return x + ' ' + dformat + plural;
}
Try, this http://jsfiddle.net/mk95J/5/:
var age = '';
function RelativeTime(x){
var ymwdhm = [ [31536000, 'year'],
[2419200, 'month'],
[604800, 'week'],
[86400, 'day'],
[3600, 'hour'],
[60, 'min'],
[1, 'sec'] ];
for(var i=0;i<7;i++) {
if(x >= ymwdhm[i][0]) {
var res = parseInt(x / ymwdhm[i][0], 10);
age += res;
age += ymwdhm[i][1];
age += res > 1 ? 's ' : ' '; // plural
RelativeTime(x - (res * ymwdhm[i][0]));
break;
}
}
}
RelativeTime( 35746121 );
document.write(age); // 1year 1month 2weeks 6days 17hours 28mins 41 secs
I would think you would want to construct your string as you go, since you want to build it up. The "else if" constructs would be good if you were only going to show the highest level of difference (only years, or only months).
Maybe something like this:
function RelativeTime(x) {
var mins = 60, hour = mins * 60; day = hour * 24,
week = day * 7, month = week * 4, year = day * 365;
var responseString = '';
if (x >= year) {
var numberOfYears = parseInt(x / year, 10);
x = x - (numberOfYears * year);
responseString += numberOfYears + ' year';
if (numberOfYears > 1) {
responseString += 's';
}
responseString += ' ';
}
if (x >= month) {
var numberOfMonths = parseInt(x / month, 10);
x = x - (numberOfMonths * month);
responseString += numberOfMonths + ' month';
if (numberOfMonths > 1) {
responseString += 's';
}
responseString += ' ';
}
return responseString;
}
// And so on ....
document.write(RelativeTime(35746121));
There are some efficiencies that could be managed within there as well (it's certainly looking like a function could come out of there to replace the almost duplicate code, and you could probably reuse some variables through there).

Categories

Resources