JavaScript to display recent birthday wishes using arrays - javascript

With below code I'm trying to write the code to display recent (from date of b'day to 15 days) b'day wishes. At present nothing is displayed. I'm new to JavaScript, so need your help.
var dates = ["02/09/2009", "12/10/2010", "02/01/2001"];
var names = ["Mac", "Jac", "Tom"];
var today = new Date();
alert(today.getMonth()+1);
//alert(today.getDay());
//alert(typeof(day));
for(var i = 0; i < dates.length; i++) {
if (dates[i].split('/')[0] = today.getDay() && dates[i].split('/')[1] = today.getMonth()+1 && dates[i].split('/')[0] <= today.getDay()+15)
{
document.getElementById("demo").innerHTML = "Wish You Happy Birthday, " + names[dates.indexOf(dates[i])] + "(" + dates[i] + ")";
}
else{
document.getElementById("demo").innerHTML = "No matches";
}
}
<p id="demo"></p>

At last, with 3rd approach I could make it work, that you all for your help!
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
// Take the difference between the dates and divide by milliseconds per day.
// Round to nearest whole number to deal with DST.
function datediff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var y = today.getFullYear();
var dates = ["10/16/" + y, "09/20/" + y, "10/2/" + y, "9/6/" + y, "10/10/" + y, "10/3/" + y];
var names = ["Mac", "Jac", "Tom", "Abhay", "Mahesh", "Jayesh"];
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
for(var i = 0; i < dates.length; i++) {
//document.getElementById("mySup").innerHTML = getGetOrdinal(dates[i].split('/')[0]);
if (datediff(parseDate(dates[i]), (today)) <= 7 && datediff(parseDate(dates[i]), (today)) >= 1)
{
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Wish You Happy Birthday, " + names[dates.indexOf(dates[i])] + "!!! (" + getGetOrdinal(dates[i].split('/')[1]) + " " + months[dates[0].split('/')[0]-1]+ ")" + "<br>";
}
}
function getGetOrdinal(n) {
var s=["th","st","nd","rd"],
v=n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}
<p><span id="demo"></span><sup id="mySup"></sup><p>

The below answer is what I had to do finally which involves functions, methods, etc. I'm sure it might be helpful to someone.
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
// Take the difference between the dates and divide by milliseconds per day.
// Round to nearest whole number to deal with DST.
function datediff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var y = today.getFullYear();
var dates = ["10/1/" + y, "09/20/" + y, "10/2/" + y, "9/6/" + y, "10/10/" + y, "10/1/" + y];
var names = ["Mac", "Jac", "Tom", "Abhay", "Mahesh", "Jayesh"];
var joingDates = ["10/16/" + y, "09/20/" + y, "10/2/" + y, "9/6/" + y, "10/10/" + y, "10/3/" + y];
var joiningyears = ["2000","2002","2010","2011","2011","2014"];
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
for(var i = 0; i < dates.length; i++) {
//document.getElementById("mySup").innerHTML = getGetOrdinal(dates[i].split('/')[0]);
if (datediff(parseDate(dates[i]), (today)) <= 7 && datediff(parseDate(dates[i]), (today)) >= 1)
{
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML +
"<li>" +
"Wishing a very" + " Happy Birthday to ".bold().fontcolor("blue") +
names[i].bold().fontcolor("Red") +
"!!! (" +
getGetOrdinal(dates[i].split('/')[1]).split('')[0] +
getGetOrdinal(dates[i].split('/')[1]).split('')[1].sup() +
getGetOrdinal(dates[i].split('/')[1]).split('')[2].sup() +
" " +
months[dates[0].split('/')[0]-1] +
")" +
"<br>";
}
}
for(var i = 0; i < joingDates.length; i++) {
if (datediff(parseDate(joingDates[i]), (today)) <= 7 && datediff(parseDate(joingDates[i]), (today)) >= 1)
{
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML +
"<li>" +
"Wishing a very " +
"Happy ".bold().fontcolor("blue") +
getGetOrdinal(y-joiningyears[i]).split('')[0].bold().fontcolor("blue") +
getGetOrdinal(y-joiningyears[i]).split('')[1].sup().bold().fontcolor("blue") +
getGetOrdinal(y-joiningyears[i]).split('')[2].sup().bold().fontcolor("blue") +
" Work Anniversary to ".bold().fontcolor("blue") +
names[i].bold().fontcolor("Red") +
" with " +
"XYZ Company".fontcolor("green").bold() +
"!!! (" +
getGetOrdinal(joingDates[i].split('/')[1]).split('')[0] +
getGetOrdinal(joingDates[i].split('/')[1]).split('')[1].sup() +
getGetOrdinal(joingDates[i].split('/')[1]).split('')[2].sup() +
" " +
months[joingDates[0].split('/')[0]-1] +
")" +
"<br>";
}
}
function getGetOrdinal(n) {
var s=["th","st","nd","rd"],
v=n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}
<p id="demo"><p>

Related

How to change Excel Column Type in JS Script to Text before Exporting Data into Excel Sheet?

I am needing to convert 5 columns to TEXT before the program writes the data to it because Excel changes my 8 digit formatted date (MM/DD/YY) that gets outputted to those columns to the Date format (MM/DD/YYYY). The outputted date needs to stay in the 8 digit format in order to rerun it as the next input file to update the system. Any suggestions would be greatly appreciated. I have tried using:
ExcelSheet.ActiveSheet.Range("E:E").TextToColumns;
but it did not work. Here's all of the code:
<script>
function js_yyyy_mm_dd_hh_mm_ss () {
now = new Date();
year = "" + now.getFullYear();
month = "" + (now.getMonth() + 1);
if (month.length == 1) { month = "0" + month; }
day = "" + now.getDate();
if (day.length == 1) { day = "0" + day; }
hour = "" + now.getHours();
if (hour.length == 1) { hour = "0" + hour; }
minute = "" + now.getMinutes();
if (minute.length == 1) { minute = "0" + minute; }
second = "" + now.getSeconds();
if (second.length == 1) { second = "0" + second; }
return month + "" + day + "" + year.substring(2) + "" + hour + "" + minute + "" + second; }
function pad(num, len) { var str = '' + num; while (str.length < len) { str = '0' + str; } return str; } function writeToExcel() { try { var loanStr; var FullRecs; var passFail; var Processed = 0; var Rejected = 0; var D9ID; var time; var date; var datetime; var row = 0; var col; var str = document.getElementById("outstr").value; var headerStr = "|Account|Stop_Code_1|SC_1_Date|Stop_Code_2|SC_2_Date|Stop_Code_3|SC_3_Date|Lockout_Code|Lock_Date|Warning_Code|Warning_Date|"; var ExcelSheet = new ActiveXObject("Excel.Application"); var excelBook = ExcelSheet.Workbooks.Add; var RSheet = excelBook.Worksheets(1); ExcelSheet.Worksheets.Activate; ExcelSheet.ActiveSheet.Name = "Removals-" + js_yyyy_mm_dd_hh_mm_ss (); var outputdate = month + "-" + day + "-" + year.substring(2); var outputtime = hour + "-" + minute; var writefilepath = document.getElementById("writepath").value; var filepath = writefilepath.substring(0, writefilepath.lastIndexOf("\\") + 1); filepath = filepath + "DEL LOAN CODE Removal" + "_" + outputdate + "_" + outputtime + "_" + "OUTPUT" + ".xlsx"; date = month + "/" + day + "/" + year.substring(2); time = hour + ":" + minute + ":" + second; RSheet.Cells(1, 3).ColumnWidth = 15; RSheet.Cells(1, 4).ColumnWidth = 15; RSheet.Cells(1, 5).ColumnWidth = 15; RSheet.Cells(1, 6).ColumnWidth = 15; RSheet.Cells(1, 7).ColumnWidth = 15; RSheet.Cells(1, 8).ColumnWidth = 15; RSheet.Cells(1, 9).ColumnWidth = 15; RSheet.Cells(1, 10).ColumnWidth = 15; RSheet.Cells(1, 11).ColumnWidth = 15; RSheet.Cells(1, 12).ColumnWidth = 15; RSheet.Cells(1, 13).ColumnWidth = 15; ExcelSheet.ActiveSheet.Cells(1, 1).value = ""; var headings = headerStr.split("|"); for(var k = 0; k < (headings.length - 1); k ++ ) { ExcelSheet.ActiveSheet.Cells(7, k + 2).value = headings[k]; } FullRecs = str.split("~~"); for(var m = 0; m < (FullRecs.length - 1); m = m + 2) { loanStr = FullRecs[m].split("^"); for(var i = 0; i < (loanStr.length - 1); i ++ ) { var fieldStr = loanStr[i].split("|"); for(var j = 0; j < (fieldStr.length); j ++ ) { ExcelSheet.ActiveSheet.Cells(row + 8, j + 2).value = fieldStr[j]; } row = row + 1; } } for(var n = 1; n <= (FullRecs.length - 1); n = n + 2) { passFail = FullRecs[n].split("|"); D9ID = passFail[0]; Processed = Processed + Number(passFail[1]); Rejected = Rejected + Number(passFail[2]); } var total = Number(Processed) + Number(Rejected) ; ExcelSheet.ActiveSheet.Cells(2, 2).value = "USER"; ExcelSheet.ActiveSheet.Cells(2, 4).value = "SUMMARY"; ExcelSheet.ActiveSheet.Cells(3, 2).value = "DATE"; ExcelSheet.ActiveSheet.Cells(3, 3).value = date; ExcelSheet.ActiveSheet.Cells(4, 2).value = "TIME"; ExcelSheet.ActiveSheet.Cells(4, 3).value = time; ExcelSheet.ActiveSheet.Cells(2, 3).value = D9ID; ExcelSheet.ActiveSheet.Cells(3, 4).value = "PROCESSED ITEMS"; ExcelSheet.ActiveSheet.Cells(3, 5).value = + Processed; ExcelSheet.ActiveSheet.Cells(4, 4).value = "REJECTED ITEMS"; ExcelSheet.ActiveSheet.Cells(4, 5).value = + Rejected; ExcelSheet.ActiveSheet.Range("B2, B3, B4, D2, D3, D4, B7, C7, D7, E7, F7, G7, H7,I7,J7,K7,L7,M7").Font.Bold = true; for( var rb = 2; rb < 5; rb ++ ) { for( var cb = 2; cb < 6; cb ++ ) { RSheet.Cells(rb, cb).BorderAround(1).LineStyle = 1; } } for( var datarow = 7; datarow <= (7 + Number(total)); datarow ++ ) { for( var datacolumn = 3; datacolumn < 14; datacolumn ++ ) { RSheet.Cells(datarow, datacolumn).BorderAround(1).LineStyle = 1; } } ExcelSheet.ActiveSheet.Columns("A:P").HorizontalAlignment = 2; ExcelSheet.ActiveSheet.Range("C2", "C4").HorizontalAlignment = 3; ExcelSheet.ActiveSheet.Range("E2", "E4").HorizontalAlignment = 3; excelBook.SaveAs(filepath); ExcelSheet.Visible = false; ExcelSheet.UserControl = true; ExcelSheet.Application.Quit(); return true; } catch(e) { if(e.number == - 2146827284) { alert(e.description + ". Please close the document."); ExcelSheet.Application.Quit(); ExcelSheet.Quit(); ExcelSheet = null; return false; } } } </script>

how to declare div and id/class in java script

I have the index.html file in that form fields are there form action is confirm.html. In confirm.html some data, I displayed using js. But showing the only table I decided to I use menus in that so more attractive for users. Whenever I'm trying to declare div(<h1>data</h1>) in confirm.html it won't be showing any data. so I decided to declare using js.
Top of the headers i have to show those menus:
document.write("<div class="Menu">");
document.write("<div class="leftmenu">");
document.write("<h4>Fegli</h4>");
document.write("<div class="Menu">");
doucment.write("<ul>");
document.write("<li>Home</li>");
document.write("</ul>");
document.write("</div>");
document.write("</div>");
document.write("</div>");
Confirm.html: code
<html>
<head>
<script type="text/javascript" src="calculate.js">
</script>
</head>
<body onload="init();">
<div id="Menu">
it wont showing on web page
</div>
</body>
</html>
Calculate.js code
// Called on body's `onload` event
var cumulative=0;
function init() {
var salary = parseInt(localStorage.getItem("salary"));
var percent = parseFloat(localStorage.getItem("percent"));
var age = parseInt(localStorage.getItem("age"));
var rAge = parseInt(localStorage.getItem("rAge"));
var sel = localStorage.getItem("sel");
var roundedSalary = parseInt(Math.ceil((salary + 2000) / 1000) * 1000); //Doing Rounding for basic column Display
var basic;
var factor = 0;
var biWeekly = 0, monthly = 0,annual = 0;
//Displaying Headers
document.write("<head>");
document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"confirm.css\">");
document.write("<title>Result</title>");
document.write("</head>");
document.write("<body>");
/* document.write("<center>")
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
document.write("<h1>" + "FEGLI CALCULATIONS ON" + " " + today + "</h1>");
document.write("</center>")
*/
document.write("<table><tr><th> Age </th><th> Annual-Salary </th><th> BiWeekly-Premium </th><th> Monthly-Premium </th><th> Annual-Premium </th><th> Cumulative-Premium </th><th>Basic </th><th> Total </th></tr>");
basic = parseInt(roundedSalary * calculateFactor(age));
//document.write("roundedSalary"+roundedSalary+"calculateFactor"+calculateFactor(age));
premium = calculateBiweekly(salary, basic, age, rAge);
biWeekly = premium[0];
monthly = premium[1];
annual = premium[2];
cumulative = premium[3];
document.write("<tr><td>" + age + "/" + (age + 1) + "</td><td>" + "$" + salary.toFixed(2) + "</td><td>" + "$" + biWeekly.toFixed(2) + "</td><td>" + "$" + monthly.toFixed(2) + "</td><td>" + "$" + annual.toFixed(2) + "</td><td>" + "$" + cumulative.toFixed(2) + "</td><td>" + "$" + basic + "</td><td>-</td></tr>");
salary = parseFloat(salary);
for (var i = age + 1; i < 101; i++) {
document.write("<tr>");
document.write("<td>" + i + "/" + (i + 1) + "</td>");
if (i < rAge) {
salary = salary + (salary * percent);
roundedSalary = parseInt(Math.ceil((salary + 2000) / 1000) * 1000);
// document.write("age"+i+"roundedSalary"+roundedSalary+"<br>");
document.write("<td>" + "$" + salary.toFixed(2) + "</td>");
} else {
salary = 0;
document.write("<td>-</td>");
}
basic = parseInt(roundedSalary * calculateFactor(i));
premium = calculateBiweekly(salary, basic, i);
biWeekly = premium[0];
monthly = premium[1];
annual = premium[2];
cumulative = premium[3];
document.write("<td>" + "$" + biWeekly.toFixed(2) + "</td>");
document.write("<td>" + "$" + monthly.toFixed(2) + "</td>");
document.write("<td>" + "$" + annual.toFixed(2) + "</td>");
document.write("<td>" + "$" + cumulative.toFixed(2) + "</td>");
document.write("<td>" + "$" + basic + "</td>");
document.write("<td>-</td>");
document.write("</tr>");
}
document.write("</table>");
document.write("</body>")
}
function calculateFactor(age) {
var factor = 0;
if (age > 35 && age < 45) {
switch (age) {
case 36:
factor = 1.9;
break;
case 37:
factor = 1.8;
break;
case 38:
factor = 1.7;
break;
case 39:
factor = 1.6;
break;
case 40:
factor = 1.5;
break;
case 41:
factor = 1.4;
break;
case 42:
factor = 1.3;
break;
case 43:
factor = 1.2;
break;
case 44:
factor = 1.1;
break;
}
} else if (age <= 35) {
factor = 2;
} else if (age >= 45) {
factor = 1;
}
return factor;
}
function calculateBiweekly(salary, basic, age) {
var biWeekly = 0;
if (salary > 0) {
biWeekly = ((basic / calculateFactor(age)) * 0.15) / 1000;
monthly = ((basic / calculateFactor(age)) * 0.325) / 1000;
} else if (salary == 0 && age <= 65) {
biWeekly = ((basic / calculateFactor(age)) * (2.455 / 2.166)) / 1000;
monthly = ((basic / calculateFactor(age)) * (2.455)) / 1000;
} else if (salary == 0 && age > 65) {
//document.write("age"+age+"salary"+salary+"<br>");
biWeekly = ((basic / calculateFactor(age)) * (2.13 / 2.166)) / 1000;
monthly = ((basic / calculateFactor(age)) * (2.13)) / 1000;
}
annual = 12 * monthly;
cumulative = cumulative+annual;
//document.write("cumulative"+cumulative+"<br>");
return [biWeekly, monthly, annual, cumulative];
}// Called on body's `onload` event
I don't recommend document.write() to create element in DOM.
You need to use document.createElement() function to create new element using javascript.
function addMenu() {
var html = '<div class="Menu">';
html += '<div class="leftmenu">';
html += '<h4>Fegli</h4>';
html += '<div class="Menu">';
html += '<ul><li>Home</li></ul>';
html += '</div>';
html += '</div>';
html += '</div>';
document.getElementById("Menu").innerHTML = html;
}
addMenu();
<div id="Menu"></div>
In your code you applied table using document.write(), you can also create table tag using document.createElement() function. check below examples:
Example 1 :
function addTable() {
var c, r, t;
t = document.createElement('table');
t.border=1;
r = t.insertRow(0);//create row
c = r.insertCell(0);///create cell
c.innerHTML = "Apple";
c = r.insertCell(1);///create second cell
c.innerHTML = "Orange";
document.getElementById("mainContainer").appendChild(t);
}
addTable();
<div id="mainContainer"></div>
Example 2 :
function addTable() {
var html = "<table border='1'><tr><td>Apple</td><td>Orange</td></tr></table>";
document.getElementById("mainContainer").innerHTML = html;
}
addTable();
<div id="mainContainer"></div>
Both example will give same result.

I am trying to simplify this code

Can this code be simplified? I am pretty sure it can be achieved by abstracting the variable and using an if else or a switch, each case would be the element ID...I'm having a a difficult time working through this.
function NoTime() {
if (shortTime == "") {
timeFormat = "N/A"
}
}
var shortTime;
var day;
var month;
var year;
var revisionDate = document.getElementById("RevisionDate").value;
shortTime = revisionDate;
day = revisionDate.substring(8, 10);
month = revisionDate.substring(4, 7);
year = revisionDate.substring(11, 15);
var timeFormat = day + " " + month + " " + year;
NoTime();
$("#RevisionDate")
.replaceWith("<div id='RevisionDate' class='col-md-12 margin-bottom-10px pad-L-15px border-1px width-174px pad-LR-3px width-227px' /></div>");
$("#RevisionDate").html(timeFormat);
var supplierPartInformationEffectiveDate = document.getElementById("SupplierPartInformationEffectiveDate")
.value;
shortTime = supplierPartInformationEffectiveDate;
day = supplierPartInformationEffectiveDate.substring(8, 10);
month = supplierPartInformationEffectiveDate.substring(4, 7);
year = supplierPartInformationEffectiveDate.substring(11, 15);
var timeFormat = day + " " + month + " " + year;
NoTime();
$("#SupplierPartInformationEffectiveDate")
.replaceWith("<div id='SupplierPartInformationEffectiveDate' class='col-md-12 margin-bottom-10px pad-LR-3px border-1px pad-LR-3px width-342px' /></div>");
$("#SupplierPartInformationEffectiveDate").html(timeFormat);
var SupplierPartInformationExpirationDate = document.getElementById("SupplierPartInformationExpirationDate")
.value;
shortTime = SupplierPartInformationExpirationDate;
day = SupplierPartInformationExpirationDate.substring(8, 10);
month = SupplierPartInformationExpirationDate.substring(4, 7);
year = SupplierPartInformationExpirationDate.substring(11, 15);
var timeFormat = day + " " + month + " " + year;
NoTime();
$("#SupplierPartInformationExpirationDate")
.replaceWith("<div id='SupplierPartInformationExpirationDate' class='col-md-12 margin-bottom-10px pad-LR-3px border-1px pad-LR-3px width-342px' /></div>");
$("#SupplierPartInformationExpirationDate").html(timeFormat);
var idArray = [ RevisionDate, SupplierPartInformationEffectiveDate, SupplierPartInformationExpirationDate ];
var attrIDArray = ["RevisionDate", "SupplierPartInformationEffectiveDate", "SupplierPartInformationExpirationDate"];
var stringIDArray = ["#RevisionDate", "#SupplierPartInformationEffectiveDate", "#SupplierPartInformationExpirationDate"];
for (i = 0; i < idArray.length; i++) {
var value = document.getElementById(attrIDArray[i]).value;
var day = value.substring(8, 10);
var month = value.substring(4, 7);
var year = value.substring(11, 15);
var timeFormat = day + " " + month + " " + year;
if (value == "") {
timeFormat = "N/A";
}
$(stringIDArray[i]).replaceWith("<div id='" + attrIDArray[i] + "' class='col-md-12 margin-bottom-10px pad-L-15px border-1px pad-LR-3px pad-TB-2px darkgrey-border-1px' /></div>");
if (stringIDArray[i] === "#RevisionDate") {
$("#RevisionDate").css("width", "227px");
} else {
$("#SupplierPartInformationEffectiveDate").css("width", "342px");
$("#SupplierPartInformationExpirationDate").css("width", "342px");
}
$(stringIDArray[i]).html(timeFormat);
}

Calender: Show dates upto next 1 week from current week

Hello friends I have a calendar with next previous button when user clicks on next button next week schedule will come if again user clicks nothing will happen I want to show dates upto next 1 week
My JavaScript for Next Button
function Next()
{
/*sunday*/
var next_sunday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+7));
var sunday = [next_sunday.getDate()];
var smonth = [next_sunday.getMonth() + 1] ;
var syear = [next_sunday.getFullYear()];
var sunday_date= syear + '-' + smonth + '-' + sunday;
alert(sunday_date);
document.getElementById("sunday").innerHTML =sunday;
/*monday*/
var next_monday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+1));
var monday = [next_monday.getDate()];
var mmonth = [next_monday.getMonth() + 1] ;
var myear = [next_monday.getFullYear()];
var monday_date= myear + '-' + mmonth + '-' + monday;
alert(monday_date);
document.getElementById("monday").innerHTML =monday;
/*Tuesday*/
var next_tuesday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+2));
var tuesday = [next_tuesday.getDate()];
var tmonth = [next_tuesday.getMonth() + 1] ;
var tyear = [next_tuesday.getFullYear()];
var tuesday_date= tyear + '-' + tmonth + '-' + tuesday;
alert(tuesday_date);
document.getElementById("tuesday").innerHTML =tuesday;
/*Wednesday*/
var next_wedday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+3));
var wednesday = [next_wedday.getDate()];
var wmonth = [next_wedday.getMonth() + 1] ;
var wyear = [next_wedday.getFullYear()];
var wednesday_date= wyear + '-' + wmonth + '-' + wednesday;
alert(wednesday_date);
document.getElementById("wednesday").innerHTML =wednesday;
/*Thursday*/
var next_thuday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+4));
var thursday = [next_thuday.getDate()];
var thmonth = [next_thuday.getMonth() + 1] ;
var thyear = [next_thuday.getFullYear()];
var thursday_date= thyear + '-' + thmonth + '-' + thursday;
alert(thursday_date);
document.getElementById("thursday").innerHTML =thursday;
/*friday*/
var next_friday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+5));
var friday = [next_friday.getDate()];
var fmonth = [next_friday.getMonth() + 1] ;
var fyear = [next_friday.getFullYear()];
var friday_date= fyear + '-' + fmonth + '-' + friday;
alert(friday_date);
document.getElementById("friday").innerHTML =friday;
/*saturday*/
var next_satday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+6));
var saturday = [next_satday.getDate()];
var samonth = [next_satday.getMonth() + 1] ;
var sayear = [next_satday.getFullYear()];
var saturday_date= sayear + '-' + samonth + '-' + saturday;
document.getElementById("saturday").innerHTML =saturday;
alert(saturday_date);
$("#date").datepicker("setDate", new Date(next_monday));
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var week_month = months[next_satday.getMonth()] ;
var week_year = [next_satday.getFullYear()];
document.getElementById("endDate").innerHTML =week_month +' '+ saturday + ',' + ' ' + week_year;
}
please suggest somthing
I got the answer I used if else loop first I have captured current week last date mean Saturday date and then compared with next saturday
Javascript
function Next()
{
// get current week saturday
var textbox_value=document.getElementById("date").value;
var current_week = new Date(textbox_value);
var next_satday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+6));
var current_satday = [next_satday.getDate()];
//alert(current_satday);
// last week saturday as per my requirement
// you can modify as per your requirement
var curr = new Date;
var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay()));
var lastday = new Date(curr.setDate(curr.getDate() - curr.getDay()+6));
var last_satday = [lastday.getDate()];
//alert(last_satday);
if(current_satday <= last_satday){
//alert('success');
/*sunday*/
var next_sunday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+7));
var sunday = [next_sunday.getDate()];
var smonth = [next_sunday.getMonth() + 1] ;
var syear = [next_sunday.getFullYear()];
var sunday_date= syear + '-' + smonth + '-' + sunday;
//alert(sunday_date);
document.getElementById("sunday").innerHTML =sunday;
/*monday*/
var next_monday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+1));
var monday = [next_monday.getDate()];
var mmonth = [next_monday.getMonth() + 1] ;
var myear = [next_monday.getFullYear()];
var monday_date= myear + '-' + mmonth + '-' + monday;
//alert(monday_date);
document.getElementById("monday").innerHTML =monday;
/*Tuesday*/
var next_tuesday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+2));
var tuesday = [next_tuesday.getDate()];
var tmonth = [next_tuesday.getMonth() + 1] ;
var tyear = [next_tuesday.getFullYear()];
var tuesday_date= tyear + '-' + tmonth + '-' + tuesday;
//alert(tuesday_date);
document.getElementById("tuesday").innerHTML =tuesday;
/*Wednesday*/
var next_wedday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+3));
var wednesday = [next_wedday.getDate()];
var wmonth = [next_wedday.getMonth() + 1] ;
var wyear = [next_wedday.getFullYear()];
var wednesday_date= wyear + '-' + wmonth + '-' + wednesday;
//alert(wednesday_date);
document.getElementById("wednesday").innerHTML =wednesday;
/*Thursday*/
var next_thuday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+4));
var thursday = [next_thuday.getDate()];
var thmonth = [next_thuday.getMonth() + 1] ;
var thyear = [next_thuday.getFullYear()];
var thursday_date= thyear + '-' + thmonth + '-' + thursday;
//alert(thursday_date);
document.getElementById("thursday").innerHTML =thursday;
/*friday*/
var next_friday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+5));
var friday = [next_friday.getDate()];
var fmonth = [next_friday.getMonth() + 1] ;
var fyear = [next_friday.getFullYear()];
var friday_date= fyear + '-' + fmonth + '-' + friday;
//alert(friday_date);
document.getElementById("friday").innerHTML =friday;
/*saturday*/
var next_satday = new Date(current_week.setDate(current_week.getDate() - current_week.getDay()+6));
var saturday = [next_satday.getDate()];
var samonth = [next_satday.getMonth() + 1] ;
var sayear = [next_satday.getFullYear()];
var saturday_date= sayear + '-' + samonth + '-' + saturday;
document.getElementById("saturday").innerHTML =saturday;
//alert(saturday_date);
$("#date").datepicker("setDate", new Date(next_monday));
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var week_month = months[next_satday.getMonth()] ;
var week_year = [next_satday.getFullYear()];
document.getElementById("endDate").innerHTML =week_month +' '+ saturday + ',' + ' ' + week_year;
}

Unique ID that gets a date in specific format?

I have code that will generate a random unique id.. but is there a way I can edit this code so that it grabs a date in a specific way like yyyy-mm-dd-0001. the last 4 digits I want it to add 1 each time the generateid button is clicked. so it will change to 0002. Here is the current code I have. Is there a function that can grab the date automatically?
var counter = 0000;
function Counter() {
if((document.getElementById("generateid").clicked == true)
{
Counter++
return counter;
}
}
function Month() {
var m = new Date();
var mm = m.getMonth() + 1;
if (mm < 10) {
mm = '0' + mm;
return mm;
}
}
function Year() {
var y = new Date();
var yy = y.getFullYear();
return yy;
}
function Day() {
var d = new Date();
var dd = d.getDate();
return dd;
}
//generate id
function guidGenerator() {
var theID = (Year() + "-" + Month() + "-" + Day() + "-" + Counter);
return theID;
}
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + guidGenerator();
document.getElementById("generateid").disabled = true;
}
You can use the following object:
var idGenerator = {
seq: 0,
generateId: function () {
this.seq++;
return (new Date()).toISOString().substring(0, 10) + '-' + ('000' + this.seq).substr(-4)
}
}
after declaration like this, try
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + idGenerator.generateId();
document.getElementById("generateid").disabled=true;
}
If you are asking for a way to keep track of how many times an ID is generated by all your site visitors using javascript alone then, no it is not possible without tying in some back end to keep track. However, the following code will do what you ask per visitor.
jsfiddle
var ttlIds = 0;
function guidGenerator() {
var S4 = function () {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + S4());
}
function generateID() {
var TheTextBox = document.getElementById("generateidtxt");
TheTextBox.value = TheTextBox.value + guidGenerator().toString().toUpperCase();
//document.getElementById("generateid").disabled=true;
ttlIds++;
if(ttlIds < 10){
ttlIds_formatted = '000'+ttlIds;
}else if(ttlIds < 100){
ttlIds_formatted = '00'+ttlIds;
}else if(ttlIds < 1000){
ttlIds_formatted = '0'+ttlIds;
}
d = new Date();
var funkydate = d.getFullYear() +'-' + (d.getMonth()+1) + '-' + d.getDate() + '-' + ttlIds_formatted;
document.getElementById("funkydate").value = funkydate;
}

Categories

Resources