I am trying to simplify this code - javascript

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

Related

JavaScript to display recent birthday wishes using arrays

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>

How is this variable still NULL

I'm in the process of writing a CasperJS script to automate a search form and capture the subsequent page. However, the search form goes to a loading splash page first until data arrives. So i added the waitForSelector function which seems to be working for some of my pages, but others return the variable name as NULL. How can that be if it is truly "waiting" for that element to be on the DOM?
casper.each(searchPages,function(casper,index){
var currentTime = new Date();
var month = currentTime.getMonth() + 2;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var dateStart = month + "/" + day + "/" + year;
month = currentTime.getMonth() + 3;
var dateEnd = month + "/" + day + "/" + year;
casper.thenOpen(url,function(){
var myfile = "data-"+year + "-" + month + "-" + day+".html";
this.evaluate(function(j) {
document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
},index);
this.evaluate(function(start) {
$("#leaveDate").val(start);
},dateStart);
this.evaluate(function(end) {
$("#returnDate").val(end);
},dateEnd);
this.evaluate(function() {
$("#OSB_btn").click();
});
this.waitForSelector('#destinationForPackage', function() {
var name = casper.evaluate(function() {
return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
});
if (name != "Going To"){
if (name == null){
console.log("it's null");
}else{
name = name.replace("/","_");
casper.capture('Captures/Searches/search_' + name + '.jpg');
console.log("Capturing search_" + name);
}
}
},function(){
console.log("Search page timed-out.");
},20000);
});
});
I was able to solve this by creating a recursive function if the element is still not available. Now i'm having a memory issue though, new question here => CasperJS running out of memory
casper.each(searchPages,function(casper,index){
loadSearch(casper,index);
});
function loadSearch(casper,index){
var currentTime = new Date();
var month = currentTime.getMonth() + 2;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var dateStart = month + "/" + day + "/" + year;
month = currentTime.getMonth() + 3;
var dateEnd = month + "/" + day + "/" + year;
casper.thenOpen(url,function(){
var myfile = "data-"+year + "-" + month + "-" + day+".html";
this.evaluate(function(j) {
document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
},index);
this.evaluate(function(start) {
$("#leaveDate").val(start);
},dateStart);
this.evaluate(function(end) {
$("#returnDate").val(end);
},dateEnd);
this.evaluate(function() {
$("#OSB_btn").click();
});
this.waitForSelector('#destinationForPackage', function() {
if (this.exists('#destinationForPackage')){
var name = casper.evaluate(function() {
return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
});
if (name != "Going To"){
if (name == null){
console.log("it's null");
}else{
name = name.replace("/","_");
casper.capture('Captures/Searches/search_' + name + '.jpg');
console.log("Capturing search_" + name);
}
}
}else{
console.log("Still doesn't exist...retry");
loadSearch(casper,index);
}
},function(){
console.log("Search page timed-out.");
},20000);
});
}

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

Adding Google Calendar event end time to script

I have a script which lists Google Calendar events with the start time, name and description but I would like to have the end time too so it reads;
5:00pm - 6:00pm - Event title - event description
Rather than just what it has at the moment which is just the start time and not the end time.
This is the script I have:
$(document).ready(GCalEvents());
function GCalEvents() {
var datenow = new Date();
var curyear = datenow.getFullYear();
var curmonth = datenow.getMonth() + 1;
var curdate = datenow.getDate();
var curhour = datenow.getHours();
var curmin = datenow.getMinutes();
var curtz = datenow.getTimezoneOffset();
//curtz = -480;
var plusmin = "-";
if (curtz <= 0) {
plusmin = "%2B";
}
curtz = Math.abs(curtz);
var curtzmin = curtz % 60;
curtz = parseInt(curtz / 60);
if (curtzmin < 10) { curtzmin = "0" + curtzmin; }
if (curtz < 10) { curtz = "0" + curtz; }
datenow = curyear + "-" + curmonth + "-" + curdate + "T" + curhour + "%3A" + curmin + "%3A00" + plusmin + curtz + "%3A" + curtzmin;
var url = "https://www.googleapis.com/calendar/v3/calendars/{calendarid}/events?alwaysIncludeEmail=false&maxResults=2&orderBy=startTime&showDeleted=false&showHiddenInvitations=false&singleEvents=true&timeMin=" + datenow + "&fields=items(start%2Csummary%2Cdescription)%2CtimeZone&key={key}";
// var url = "https://www.googleapis.com/calendar/v3/calendars/{calendarid}/events?alwaysIncludeEmail=false&maxResults=2&orderBy=startTime&showDeleted=false&showHiddenInvitations=false&singleEvents=true&timeMin=" + datenow + "&fields=items(start%2Csummary%2Cdescription)%2CtimeZone&key={key}";
$.getJSON(url, function(data) {
var event_start_date_new = new Date();
event_start_date_new.setDate(event_start_date_new.getDate() - 1);
for(i in data['items']) {
item = data['items'][i];
// event title
var event_title = item.summary;
var event_description = item.description;
// event start date/time
var event_start_date = new Date(item.start.dateTime);
// format the date and time
var month = event_start_date.getMonth();
var day = event_start_date.getDay();
var date = event_start_date.getDate();
var daysArr = new Array();
daysArr[0] = "Sunday";
daysArr[1] = "Monday";
daysArr[2] = "Tuesday";
daysArr[3] = "Wednesday";
daysArr[4] = "Thursday";
daysArr[5] = "Friday";
daysArr[6] = "Saturday";
var monthsArr = new Array();
monthsArr[0] = "January";
monthsArr[1] = "February";
monthsArr[2] = "March";
monthsArr[3] = "April";
monthsArr[4] = "May";
monthsArr[5] = "June";
monthsArr[6] = "July";
monthsArr[7] = "August";
monthsArr[8] = "September";
monthsArr[9] = "October";
monthsArr[10] = "November";
monthsArr[11] = "December";
var hour = event_start_date.getHours();
var min = event_start_date.getMinutes();
if (min < 10) { min = "0" + min; }
if (hour < 11) {
var ampm = "am";
if (hour == 0) { hour = 12; }
} else {
var ampm = "pm";
if (hour > 12) { hour = hour - 12; }
}
if (hour < 10) { hour = " " + hour; }
var event_start_str = daysArr[day] + ", " + monthsArr[month] + " " + date;
var event_time_str = hour + ":" + min + " " + ampm;
if (event_start_date.getDate() != event_start_date_new.getDate()) {
event_start_str = "<div class=\"calendar_date\"><strong>" + event_start_str + "</strong></div>";
event_start_date_new = event_start_date;
} else {
event_start_str = "";
};
// Render the event
$("#gcal-events").last().before("<div class=\"calendar_item\"><li>" + event_time_str + " - " + event_title + "<p><small>" + event_description + "</small></p></ul>" + "</li></div>");
}
});
};
If anyone is able to help with that to reversion the current script, that would be great.
The Events resource returns start and end dates as well (JSON format that has date, dateTime, timeZone attributes).
Based on your code, you're not using the end attribute which is why you're not having any values for the end date displayed. Your code for the start date is alright, so you can just re-implement it for the end attribute.
Hope this helps!

Javascript Date constructor ignoring parameters

Supposedly, I should be able to create an arbitrary date using the Date constructor as demonstrated here and referenced here
Where am I going wrong? Please notice that on the last few lines of prettyDateToTimeStamp, I modify the month and day to verify that the Date constructor is doing something - but it is not noticing anything I pass in and just returns the current date.
Here is my code below: and a jsfiddle
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the full year of todays date.</p>
<p id="demo2">todays date.</p>
<p id="demo3">some other date.</p>
<button onclick="showdates()">Try it</button>
<script>
function showdates() {
var d = Date.now();
var dv = document.getElementById('demo');
dv.innerHTML = d;
var pd = prettyDate(d);
dv = document.getElementById('demo2');
dv.innerHTML = pd;
var ts = prettyDateToTimeStamp(pd);
dv = document.getElementById('demo3');
dv.innerHTML = ts;
}
function prettyDate(javaScriptTimeStamp) {
var dt = new Date(javaScriptTimeStamp);
var year = dt.getFullYear();
var month = dt.getMonth() + 1;
var day = dt.getDate();
var hours = dt.getHours();
var minutes = dt.getMinutes();
var seconds = dt.getSeconds();
return month + "/" + day + "/" + year + " " + hours + ":" + minutes + ":" + seconds;
}
function prettyDateToTimeStamp(prettyDate) {
var halves = prettyDate.split(' ');
console.log("halves: " + halves);
var calpart = halves[0];
console.log("calpart : " + calpart );
var clockpart = halves[1];
console.log("clockpart : " + clockpart );
var calbits = calpart.split('/');
console.log("calbits : " + calbits );
var timebits = clockpart.split(':');
console.log("timebits : " + timebits );
var year = parseInt(calbits[2],10);
console.log("year : " + year );
var month = parseInt(calbits[0],10);
console.log("month : " + month );
var day = parseInt(calbits[1],10);
console.log("day : " + day );
var hour = parseInt(timebits[0],10);
console.log("hour : " + hour );
var min = parseInt(timebits[1],10);
console.log("min : " + min );
var sec = parseInt(timebits[2],10);
console.log("sec : " + sec );
month += 3; // change month radically to demonstrate the problem
console.log("month is now: " + month );
day += 7; // change day too
console.log("day is now: " + day );
var ts = Date(year,month,day,hour,min,sec,0);
console.log("ts : " + ts ); // date ctor paramters completely ignored...?
return ts;
}
</script>
</body>
</html>
omg, I have to say "new" Date .... (I've been using Python too much lately)
corrected code now works.
function prettyDateToTimeStamp(prettyDate) {
var halves = prettyDate.split(' ');
var calpart = halves[0];
var clockpart = halves[1];
var calbits = calpart.split('/');
var timebits = clockpart.split(':');
var year = parseInt(calbits[2],10);
var month = parseInt(calbits[0],10);
var day = parseInt(calbits[1],10);
var hour = parseInt(timebits[0],10);
var min = parseInt(timebits[1],10);
var sec = parseInt(timebits[2],10);
month += 3; // change month radically to demonstrate the problem
day += 7; // change day too
var ts = new Date(year,month,day,hour,min,sec,0); // you have to use NEW here!
return ts;
}

Categories

Resources