How to get the exact year from date of birth? - javascript

how do you get the age from 6 characters?
(API giving me only this value: 16010119951, to find the age, first 6 characters are yymmdd. How do I know 16 is: 2016 or 1916 or 1816? )
function get_age(input) {
var y = input.charAt(0) + input.charAt(1);
var m = input.charAt(2) + input.charAt(3);
var d = input.charAt(4) + input.charAt(5);
y = parseInt(y);
m = parseInt(m);
d = parseInt(d);
if(m<10) { m = '0' + m; }
if(d<10) { d = '0' + d; }
var ymd = d + '-' + m + '-' + y;
return ymd;
}

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

convert time to to 12 hour by manipulate string

"2015-06-23 14:00:00"
I tried to format above date time into 12 hour base but stuck in somewhere.
function formatDate(raw_date){
var right = raw_date.substring(10, 0);
var hours = ((right[0].substring(2,0) + 11) % 12 + 1);
var min = raw_date.substring(14,16);
var suffix = right[1] >= 12 ? "PM":"AM";
right[1] = ((right[1] + 11) % 12 + 1) + suffix;
return hours + ':' + min + ' ' + suffix;
}
Can someone help? My desired output is "23/06/2015 02:00 PM"
Try this:
function formatDate(raw_date) {
var right = new Date(raw_date);
var currentHours = right.getHours();
var timeOfDay = (currentHours < 12) ? "AM" : "PM";
if (currentHours > 12) {
currentHours -= 12;
}
return (right.getDate() + '/' + right.getMonth()+ '/' + right.getFullYear() +" "+ currentHours+ ":"+right.getMinutes() + timeOfDay);
}
alert(formatDate("2015-06-23 14:00:00"));
Demo
Solution based on your code:
function formatDate(raw_date){
var year = raw_date.substring(0,4);
var month = raw_date.substring(5,7);
var day = raw_date.substring(8,10);
var right = raw_date.substring(10);
var hours = ((right.substring(0,3))% 12 );
var min = raw_date.substring(14,16);
var suffix = right.substring(0,3) >= 12 ? "PM":"AM";
return day + "/"+month+"/"+year+" "+hours + ':' + min + ' ' + suffix;
}
You should follow a simple flow.
Try to break down the input -> convert them _> and then sum them up:
function formatDate(raw_date){
var right = raw_date.substring(0, 10);
var year=right.substring(0,4);
var month=right.substring(5,7);
var day=right.substring(8,10);
right=day+"/"+month+"/"+year;
var left=raw_date.substring(11, raw_date.length);
var hours = left.substring(0,2);
var suffix = hours >= 12 ? "PM":"AM";
hours=hours-12;
if(hours<10) hours='0'+hours;
var min = left.substring(3,5);
left=hours+":"+min+" "+suffix;
return right + ' ' + left;
}

How to convert this to show 12 hour clock? [duplicate]

This question already has answers here:
How do you display JavaScript datetime in 12 hour AM/PM format?
(31 answers)
Closed 8 years ago.
Currently shows the time in a 24 Hour clock format. Can this be chnaged to show a 12 Hour clock with AM or PM? Thanks
function startTime() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
Yes, if you want to continue formatting manually, you can use something like this:
element.innerHTML = (h > 12 ? h - 12 : h) + ":" + m + ":" + s + (h >= 12 ? " PM" : " AM");
new Date().toLocaleTimeString()
/* returned value: (String)
eg. 11:25:50 AM
or 8:08:41 PM
*/
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
var ampm = h >= 12 ? 'pm' : 'am';
h = h % 12;
h = h ? h : 12;
m = m < 10 ? '0' + m : m;
var strTime = h + ':' + m + ':' + s +' ' + ampm;
document.getElementById('txt').innerHTML = strTime;
var t = setTimeout(function () { startTime() }, 500);
}
function checkTime(i) {
if (i < 10) { i = "0" + i }; // add zero in front of numbers < 10
return i;
}
DEMO

Displaying the time in 12hr format

I need your help
If the code below is able to get the date in my requested format of: dd/mm/yyyy
How do I go about getting the time in a 12hr format ie. 13:53 is 1:53pm
Thank you
<script type="text/javascript">
function test() {
var d = new Date(),
m = d.getMonth() + 1,
xdate = [d.getDate(), (m < 10) ? '0' + m : m, d.getFullYear()].join('/');
var t = d.format("h:mm ss");
alert("the date is:" + xdate + "time is:" + t)
}
</script>
Demo jsFiddle
JS
var d = new Date();
alert("the date is: " + d.toLocaleDateString() + "time is: " + d.toLocaleTimeString());
Note: these functions aren't exactly cross browser supported
Use this:
var d = new Date(),
m = d.getMonth()+1,
x = [d.getDate(), (m < 10) ? '0' + m : m, d.getFullYear()].join('/'),
y = d.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
alert(x +" "+ y)
Taken from:
How do you display javascript datetime in 12 hour AM/PM format?
It is not that difficult. Try this one out :
JS:
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = dt.getHours();
var hours = ((hours24 + 11) % 12) + 1;
formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "pm" : "am"].join(" ");
}
return formatted;
}
})();
console.log(formatTime(new Date()));
Find the working fiddle here : http://jsfiddle.net/rRd2P/1/

Categories

Resources