Converting the code below to display the date in european format - javascript

the IsDateValid function below validates date in an american format.What do i change to convert it to validate the date in a European format. when the validate works a user is able to enter the date by simply entering a + or - sign depending on what they want i.e. a past date, or a future date.
function IsLeapYear(year) {
//Convert from string to number
year = year - 0;
if ((year/4) != Math.floor(year/4)) return false;
if ((year/100) != Math.floor(year/100)) return true;
if ((year/400) != Math.floor(year/400)) return false;
return true;
} //function IsLeapYear...
function countChar(str, daChar) {
//See how many of 'dachar' are in 'str' and return as daCount
var daCount=0;
for (i = 0; i < str.length; i++) {
if (str.charAt(i) == daChar)
//increment count each time we find daChar in str
daCount++;
}
return daCount;
} //function countChar...
function IsDateValid(dateField, noDateRqrd) {
//If no date is required and they didn't enter one, then go back
if (((typeof noDateRqrd != "undefined") && (dateField.value.length == 0))||dateField.value.length == 0)
return null;
//We're going to check this date so go on
var GoodLength = false;
var msg='';
var daysOfMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var daysOfMonthLY = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
//Make sure they have the right number of '/'
var cCount=countChar(dateField.value,'/');
//force a date value
if (dateField.value.length >= 3) {
//alert('cc: ' + cCount + 'fl: ' + dateField.value.length);
if ((cCount == 1) && (dateField.value.length >= 3) && (dateField.value.length <= 5))
GoodLength=true;
else if ((cCount == 2) && (dateField.value.length >= 4) && (dateField.value.length <= 10))
GoodLength=true;
}
//If the length is good, then let's check the contents of the dateField
if (GoodLength == true) {
var firstslash=dateField.value.indexOf('/')+1; //must add 1 to get real position
var lastslash=dateField.value.lastIndexOf('/')+1;
/****************************
Note: substr is not included in CFStudio so 'substr' will not be bolded & blue
*****************************/
var month=dateField.value.substr(0,firstslash-1);
if ((!isNaN(month)) && (month < 13)){
if (firstslash != lastslash) {
//alert(dateField.value);
var day=dateField.value.substr(firstslash,lastslash-firstslash-1); //lastslash-firstslash+1
//We only need to tell it where to cut off the first char
var year=dateField.value.substr(lastslash);
//Access dates can range from 100 to 9999.
//SQL Server dates can range from 1753 to 9999.
//Since this code can run for either db, we'll use the more restrivtive date of 1753.
//The length test will catch any date > 9999.
if (!isNaN(day)&&!isNaN(year)&&(year.length < 5)){
//If there isn't a year value, then put in the current year
if (year.length == 0) {
//There is no year so we only need to get day
var day=dateField.value.substr(firstslash,lastslash-firstslash-1);
//Since they didn't enter a year, we'll use the current year
var now = new Date();
year=now.getFullYear();
dateField.value = month + "/" + day + "/" + year;
} else if ((year.length == 1) || (year.length == 2)) {
var tmpDate = new Date(dateField.value);
//Programmer's Note: entered value of "00" would be return as "1900" by getFullYear
tmpDate_yyyy = tmpDate.getFullYear()-1900; //Get 4 dig date and reindex without centuary
//alert('tmpDate_yyyy: ' + tmpDate_yyyy);
if (tmpDate_yyyy < 100) { //If less than 100, then we're in 20th centuary
if (tmpDate_yyyy < 60) //do 00 to 59 as 20xx
tmpDate.setFullYear(2000 + tmpDate_yyyy); //reset year to 21st centuary
else //do 60 to 99 as 19xx
tmpDate.setFullYear(1900 + tmpDate_yyyy); //reset year to 20th centuary
//Have to do it the hard way or we'll also get day, time, etc. which we don't want here
//getMonth is zero based so it returns a number one less that we want
}
dateField.value = tmpDate.getMonth()+1 + "/" + tmpDate.getDate() + "/" + tmpDate.getFullYear();
} else if ((year.length == 4)&&(year > 1752)) {
dateField.value = day + "/" + Month + "/" + year;
} else {
msg= 'The date you entered is not valid: ' + dateField.value + '.';
}//if
} else {
msg= 'The date you entered is not valid: ' + dateField.value + '.';
} //if
} else {
//There is no year so we only need to get day
var day=dateField.value.substr(firstslash);
if (!isNaN(day)) {
//Since they didn't enter a year, we'll use the current year
var now = new Date();
var year=now.getFullYear();
dateField.value = month + "/" + day + "/" + year;
} else {
msg= 'The day you entered is not valid: ' + dateField.value + '.';
} //if
}
//alert('m: ' + month + ' d: ' + day + ' y:' + year);
if ((day==0)||(IsLeapYear(year) && day > daysOfMonthLY[month-1])||(!IsLeapYear(year) && day > daysOfMonth[month-1]))
msg= 'The date you entered is not valid: ' + dateField.value + '.';
} else {
msg='The month you entered is not valid: ' + month + '.';
}
} else {
if (dateField.value.length == 0) {
msg= 'You must enter enter a valid Date.';
} else if ((dateField.value.toLowerCase() == 'today')||(dateField.value.toLowerCase() == 'now')) {
var now = new Date();
var day=now.getDate();
var month=now.getMonth()+1; //Have to add 1 to get correct month
var year=now.getFullYear();
dateField.value = month + "/" + day + "/" + year;
} else if ((dateField.value.indexOf('+') == 0)||(dateField.value.indexOf('-') == 0)) {
//alert('in: ' + dateField.value + ', NaN: ' + isNaN(dateField.value));
if (!isNaN(dateField.value)) {
var now = new Date();
var nowMS = now.getTime(); //Get the current time in milliseconds
//Add the number of milliseconds in a day times the number of days requested
//Use the Math.floor to make sure we only get whole days in case they add a decimal value
now.setTime(nowMS + Math.floor((dateField.value * 1000*60*60*24)));
var day=now.getDate();
var month=now.getMonth()+1; //Have to add 1 to get correct month
var year=now.getFullYear();
dateField.value = month + "/" + day + "/" + year;
} else
msg= 'The proper format, +#, or -#, with no spaces in between: e.g., "+6", or "-2". You entered: "' + dateField.value + '".';
} else
msg= '146: The date you entered is not valid: "' + dateField.value + '".';
}
if(msg.length > 0) {
if (typeof noDateRqrd == 'undefined') {
var lastLine="Select 'OK' to re-enter value, or 'Cancel' to enter the current date.\n\n"
} else {
var lastLine="Select 'OK' to re-enter value, or 'Cancel' to clear the date.\n\n"
}
var conmsg ="\n\n____________________________________________________\n\n" +
msg +
"\n\n____________________________________________________\n\n" +
"A valid date must contain at least one forward slash '/' as well as a day and a month.\n" +
"If you leave the year blank, then the current year will be inserted.\n\n" +
"The allowable date range is from 1/1/1753 to 12/31/9999.\n\n" +
lastLine
if (confirm(conmsg))
dateField.focus();
else {
if (typeof noDateRqrd == 'undefined') {
//get the current time
var Now=new Date();
dateField.value=Now.getMonth()+1 + "/" + Now.getDate() + "/" + Now.getFullYear();
} else {
dateField.value="";
}
}
return false;
} else
return true;
} //function IsDateValid

Related

Google Sheet script - send an email reminder based on due date

I've looked around and have bits and pieces but can't put the puzzle together. I'm attempting to create a script that will send an email depending on the date. I.E. if a "response" is due on 08/30 it will send a response 2 weeks prior, 1 week prior, and the date of.
Basically I'm looking for the script to capture a range of cells, identify a due date, which will be populated in a column, match it to the current date and send out reminder emails.
The script runs but it will not send me an email.
Here is the code:
function emailAlert() {
// today's date information
var today = new Date();
var todayMonth = today.getMonth() + 1;
var todayDay = today.getDate();
var todayYear = today.getFullYear();
// 1 week from now
var oneWeekFromToday = new Date();
oneWeekFromToday.setDate(oneWeekFromToday.getDate() + 14);
var oneWeekMonth = oneWeekFromToday.getMonth() + 1;
var oneWeekDay = oneWeekFromToday.getDate();
var oneWeekYear = oneWeekFromToday.getFullYear();
// 2 weeks from now
var twoWeeksFromToday = new Date();
twoWeeksFromToday.setDate(twoWeeksFromToday.getDate() + 14);
var twoWeeksMonth = twoWeeksFromToday.getMonth() + 1;
var twoWeeksDay = twoWeeksFromToday.getDate();
var twoWeeksYear = twoWeeksFromToday.getFullYear();
// getting data from spreadsheet
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 100; // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, 999);
var data = dataRange.getValues();
//looping through all of the rows
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var expireDateFormat = Utilities.formatDate(
new Date(row[6]),
'ET',
'MM/dd/yyyy'
);
// email information
var subject = '';
var message =
' A grievance ' +
'\n' +
' Name: ' +
row[0] +
'\n' +
' Grievance ID: ' +
row[2] +
'\n' +
' College: ' +
row[5] +
'\n' +
' Department: ' +
row[6] +
'\n' +
' Article/Policy Violation: ' +
row[7] +
'\n' +
' Status: ' +
row[9] +
'\n' +
' Response Due Date: ' +
expireDateFormat;
//expiration date information
var expireDateMonth = new Date(row[12]).getMonth() + 1;
var expireDateDay = new Date(row[12]).getDate();
var expireDateYear = new Date(row[12]).getFullYear();
//checking for today
if (
expireDateMonth === todayMonth &&
expireDateDay === todayDay &&
expireDateYear === todayYear
) {
var subject =
'A Grievance Is Due Today: ' + row[7] + ' - ' + expireDateFormat;
MailApp.sendEmail('myemail.mail', subject, message);
Logger.log('todayyyy!');
}
//checking for 1 week from now
Logger.log('1 week month, expire month' + oneWeekMonth + expireDateMonth);
if (
expireDateMonth === oneWeekMonth &&
expireDateDay === oneWeekDay &&
expireDateYear === oneWeekYear
) {
var subject =
'A grievance is due in 1 week: ' +
row[7] +
' - ' +
expireDateFormat;
MailApp.sendEmail('myemail.mail', subject, message);
Logger.log('1 week from now');
}
//checking for 2 weeks from now
Logger.log('2 weeks month, expire month' + twoWeeksMonth + expireDateMonth);
if (
expireDateMonth === twoWeeksMonth &&
expireDateDay === twoWeeksDay &&
expireDateYear === twoWeeksYear
) {
var subject =
'A grievance is due in 2 weeks: ' +
row[7] +
' - ' +
expireDateFormat;
MailApp.sendEmail('myemail.mail', subject, message);
Logger.log('2 weeks from now');
}
}
}

Ignore Sundays from jQuery date range picker

I'm using the following jQuery date range picker library : http://longbill.github.io/jquery-date-range-picker/
I would like to remove / hide all Sundays from all date range pickers while keeping a normal behavior on the date range pickers.
I tried to do something with beforeShowDay option :
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = '';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
but it only "disables" all Sundays whereas I want to remove / hide them:
Here's the fiddle I'm working on : https://jsfiddle.net/maximelafarie/dnbd01do/11/
EDIT:
Updated fiddle with #Swanand code: https://jsfiddle.net/maximelafarie/dnbd01do/18/
You could do it with just a little CSS but it does leave a gap:
.week-name th:nth-child(7),
.month1 tbody tr td:nth-child(7) {
display: none;
}
Hope this helps a little.
You need do changes in two functions in your daterangepicker.js file:
createMonthHTML()
function createMonthHTML(d) { var days = [];
d.setDate(1);
var lastMonth = new Date(d.getTime() - 86400000);
var now = new Date();
var dayOfWeek = d.getDay();
if ((dayOfWeek === 0) && (opt.startOfWeek === 'monday')) {
// add one week
dayOfWeek = 7;
}
var today, valid;
if (dayOfWeek > 0) {
for (var i = dayOfWeek; i > 0; i--) {
var day = new Date(d.getTime() - 86400000 * i);
valid = isValidTime(day.getTime());
if (opt.startDate && compare_day(day, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(day, opt.endDate) > 0) valid = false;
days.push({
date: day,
type: 'lastMonth',
day: day.getDate(),
time: day.getTime(),
valid: valid
});
}
}
var toMonth = d.getMonth();
for (var i = 0; i < 40; i++) {
today = moment(d).add(i, 'days').toDate();
valid = isValidTime(today.getTime());
if (opt.startDate && compare_day(today, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(today, opt.endDate) > 0) valid = false;
days.push({
date: today,
type: today.getMonth() == toMonth ? 'toMonth' : 'nextMonth',
day: today.getDate(),
time: today.getTime(),
valid: valid
});
}
var html = [];
for (var week = 0; week < 6; week++) {
if (days[week * 7].type == 'nextMonth') break;
html.push('<tr>');
for (var day = 0; day < 7; day++) {
var _day = (opt.startOfWeek == 'monday') ? day + 1 : day;
today = days[week * 7 + _day];
var highlightToday = moment(today.time).format('L') == moment(now).format('L');
today.extraClass = '';
today.tooltip = '';
if (today.valid && opt.beforeShowDay && typeof opt.beforeShowDay == 'function') {
var _r = opt.beforeShowDay(moment(today.time).toDate());
today.valid = _r[0];
today.extraClass = _r[1] || '';
today.tooltip = _r[2] || '';
if (today.tooltip !== '') today.extraClass += ' has-tooltip ';
}
var todayDivAttr = {
time: today.time,
'data-tooltip': today.tooltip,
'class': 'day ' + today.type + ' ' + today.extraClass + ' ' + (today.valid ? 'valid' : 'invalid') + ' ' + (highlightToday ? 'real-today' : '')
};
if (day === 0 && opt.showWeekNumbers) {
html.push('<td><div class="week-number" data-start-time="' + today.time + '">' + opt.getWeekNumber(today.date) + '</div></td>');
}
if(day == 0){
html.push('<td class="hideSunday"' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}else{
html.push('<td ' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}
}
html.push('</tr>');
}
return html.join('');
}
In this function i have added class hideSunday while pushing the element.
The 2nd function is getWeekHead():
function getWeekHead() {
var prepend = opt.showWeekNumbers ? '<th>' + translate('week-number') + '</th>' : '';
if (opt.startOfWeek == 'monday') {
return prepend + '<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>' +
'<th class="hideSunday">' + translate('week-7') + '</th>';
} else {
return prepend + '<th class="hideSunday">' + translate('week-7') + '</th>' +
'<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>';
}
}
In this file, I have added class to week-7 header.
CSS:
.hideSunday{display:none;}
Please note, I have not checked all the scenario but it will do trick for you.
I finally ended up by letting the Sundays appear (but completely disabling them).
These questions inspired me :
Moment.js - Get all mondays between a date range
Moment.js: Date between dates
So I created a function as follows which returns an array that contains the "sundays" (or whatever day you provide as dayNumber parameter) in the date range you selected:
function getDayInRange(dayNumber, startDate, endDate, inclusiveNextDay) {
var start = moment(startDate),
end = moment(endDate),
arr = [];
// Get "next" given day where 1 is monday and 7 is sunday
let tmp = start.clone().day(dayNumber);
if (!!inclusiveNextDay && tmp.isAfter(start, 'd')) {
arr.push(tmp.format('YYYY-MM-DD'));
}
while (tmp.isBefore(end)) {
tmp.add(7, 'days');
arr.push(tmp.format('YYYY-MM-DD'));
}
// If last day matches the given dayNumber, add it.
if (end.isoWeekday() === dayNumber) {
arr.push(end.format('YYYY-MM-DD'));
}
return arr;
}
Then I call this function in my code like that:
$('#daterange-2')
.dateRangePicker(configObject2)
.bind('datepicker-change', function(event, obj) {
var sundays = getDayInRange(7, moment(obj.date1), moment(obj.date1).add(selectedDatesCount, 'd'));
console.log(sundays);
$('#daterange-2')
.data('dateRangePicker')
.setDateRange(obj.value, moment(obj.date1)
.add(selectedDatesCount + sundays.length, 'd')
.format('YYYY-MM-DD'), true);
});
This way, I retrieve the amount of sundays in the date range I selected. For example, if there's two sundays in my selection (with sundays.length), I know I have to set two additional workdays to the user selection (in the second date range picker).
Here's the working result:
With the above screenshot, you can see the user selected 4 workdays (5 with sunday but we don't count it). Then he click on the second calendar and the 4 workdays automatically apply.
Here's the result if the period apply over a sunday (we add one supplementary day and Xfor X sundays in the period):
Finally, here's the working fiddle: https://jsfiddle.net/maximelafarie/dnbd01do/21/
I want to thank any person that helped me. The question was hard to explain and to understand.
You can also do it by setting a custom css class and use it in beforeShowDay like below
.hideSunDay{
display:none;
}
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = t.getDay() !== 0 ? '' : 'hideSunDay';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
But it only hides the sundays beginning from current day.
Here is a working fiddle
https://jsfiddle.net/dnbd01do/16/

Get Date string value from Date and Time field in CRM using JavaScript

I am trying to get the date string value(mm/dd/yyyy)from a custom date and time field and set the returned value back into the custom field. I found this script and modified it but it does not seem to work. When I step through the code it breaks on var year = startDate.getFullYear() + ""; Any ideas what I am doing wrong? Thanks.
function ConcatChainsAuth() {
var startDate = Xrm.Page.getAttribute("new_dateauthorized").getValue();
if (startDate != null) {
var year = startDate.getFullYear() + "";
var month = (startDate.getMonth() + 1) + "";
var day = startDate.getDate() + "";
var dateFormat = month + "-" + day + "-" + year;
Xrm.Page.getAttribute("new_dateauthorized").setValue(dateFormat);
}
var lookupObject = Xrm.Page.getAttribute("new_chain");
if (lookupObject != null) {
var lookUpObjectValue = lookupObject.getValue();
if ((lookUpObjectValue != null)) {
var Chain = lookUpObjectValue[0].name;
}
}
var lookupObject = Xrm.Page.getAttribute("new_package");
if (lookupObject != null) {
var lookUpObjectValue = lookupObject.getValue();
if ((lookUpObjectValue != null)) {
var Package = lookUpObjectValue[0].name;
}
}
var concatedField = Chain + "-" + Package + "-" + dateFormat;
Xrm.Page.getAttribute("new_name").setValue(concatedField);
Xrm.Page.data.entity.save();
}
Assuming that new_dateauthorized is a CRM date field, then Xrm.Page.getAttribute("new_dateauthorized").getValue() will return a Date object.
In which case you can just manipulate the Date object, like so:
var currentDate = Xrm.Page.getAttribute("new_dateauthorized").getValue();
currentDate.setMonth(currentDate.getMonth() + 1);
Xrm.Page.getAttribute("new_dateauthorized").setValue(currentDate);
However, adding months in this fashion fails in some cases, check out the comments here for more info.

Last array element keeps returning false

I have a time/date converter. When the user enters "130" for example it returns "06/07/2016 01:30:00" when they enter "6 7 16" for example it returns "06/07/2016 00:00:00" but when the user enters "6 7 16 130" for example it returns "06/07/2016 false:00"
Here is my relevant code (can show more if need be):
function checkDateTime(val) {
var nowDate = new Date();
var month, day, year, time;
var ar;
if (eval(val)) {
var tval = val.value;
ar = tval.split(' ');
if (ar.length === 3) { // i.e. if it's supposed to be a date
ar[0] = month;
ar[1] = day;
ar[2] = year;
document.getElementById("FromDate").value = CheckDate(val) + ' ' + '00:00:00';
//checkDate(ar[0] + ' ' + ar[1] + ' ' + ar[2]);
}
//alert(LeftPadZero(ar[0]) + ' ' + LeftPadZero(ar[1]) + ' ' + LeftPadZero(ar[2]));
//alert(CheckDate(ar[0] + ' ' + ar[1] + ' ' + ar[2]));
if (ar.length === 1) { // if it's a time
ar[0] = time;
var MM = nowDate.getMonth() + 1;
var DD = nowDate.getDate();
var Y = nowDate.getFullYear();
var nowDateFormat = LeftPadZero(MM) + '/' + LeftPadZero(DD) + '/' + Y;
alert(ar[0]);
document.getElementById("FromDate").value = nowDateFormat + ' ' + checktime(val) + ':00';
}
if (ar.length === 4) { // if date and time
ar[0] = month;
// alert(ar[0]);
ar[1] = day;
// alert(ar[1]);
ar[2] = year;
// alert(ar[2]);
ar[3] = time;
// alert(ar[3]);
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(val) + ':00';
// alert(ar[0] + ' ' + ar[1] + ' ' + ar[2] + ' ' + ar[3]);
}
}
}
function CheckDate(theobj) {
var isInvalid = 0;
var themonth, theday, theyear;
var arr;
if (eval(theobj)) {
var thevalue = theobj.value;
arr = thevalue.split(" ");
if (arr.length < 2) {
arr = thevalue.split("/");
if (arr.length < 2) {
arr = thevalue.split("-");
if (arr.length < 2) {
isInvalid = 1;
}
}
}
if (isInvalid == 0) {
themonth = arr[0];
theday = arr[1];
if (arr.length == 3) {
theyear = arr[2];
} else {
theyear = new Date().getFullYear();
}
if (isNaN(themonth)) {
themonth = themonth.toUpperCase();
//month name abbreviation array
var montharr = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
for (i = 0; i < montharr.length; i++) {
//if the first 3 characters of month name matches
if (themonth.substring(0, 3) == montharr[i]) {
themonth = i + 1;
break;
}
}
} else {
if (themonth < 1 || themonth > 12) {
isInvalid = 1;
}
}
}
if (isNaN(themonth) || isNaN(theday) || isNaN(theyear)) {
isInvalid = 1;
}
if (isInvalid == 0) {
var thedate = LeftPadZero(themonth) + "/" + LeftPadZero(theday) + "/" + LeftPadZero(theyear);
return thedate;
} else {
return false;
}
}
}
function checktime(x) {
var tempchar = new String;
tempchar = MakeNum(x);
if (tempchar != '' && tempchar.length < 4) {
//e.g., if they enter '030' make it '0030'
if (tempchar.length == 3) {
tempchar='0' + tempchar;
}
//e.g, if they enter '11' make it '1100'
if (tempchar.length == 2) {
tempchar=tempchar + '00';
}
//e.g, if they enter '6' make it '0600'
if (tempchar.length == 1) {
tempchar='0' + tempchar + '00';
}
}
if (tempchar==null || tempchar == '') {
return false;
}
else {
if (tempchar=='2400') {
return false;
}else{
var tempnum= new Number(tempchar);
var swmin = new Number(tempnum % 100);
var swhour = new Number((tempnum-swmin)/100);
if (swhour < 25 && swmin < 60) {
x = LeftPadZero(swhour) + ":" + LeftPadZero(swmin);
return x;
}
else {
return false;
}
}
}
return false;
/*
if(eval(changecount)!=null){
changecount+=1;
}
*/
}
function MakeNum(x) {
var tstring = new String(x.value);
var tempchar = new String;
var f = 0;
for (var i = 0; i < tstring.length; i++) {
// walk through the string and remove all non-digits
chr = tstring.charAt(i);
if (isNaN(chr)) {
f=f;
}
else {
tempchar += chr;
f++;
}
}
return tempchar;
}
I have tried numerous things to figure out why the time element returns false in an array of length 4, but not an array length 1 for some reason, including setting various alerts and checking the console. I have googled this problem several times and came up empty.
To reiterate, my problem is that the time element returns false in an array of 4, and what I am trying to accomplish is for the user to input a date and time and have them both formatted and displayed correctly.
Can anybody help and/or offer any advice and/or suggestions? Thanks!
Edit: user enters '130' should convert to '06/07/2016(today's date) 01:30:00'
6 7 16 should convert to '06/07/2016 00:00:00'
6 7 16 130 should convert to '06/07/2016 01:30:00'
There seems to be some missing parts here... various functions and whatever input type these ones need are excluded from your post... However, taking a guess, I'm going to say that when you are making your final "checktime" call, rather than passing the full "val" variable, you should just be passing the last chunk of your split input, "ar[3]" in this case. That way, only that piece is evaluated by the function.
IE:
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(val) + ':00';
should be
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(ar[3]) + ':00';
Again, this is just a guess due to the missing pieces.
Edit:
After getting some additional details, the issue DOES seem to be in the data being sent to the checktime function, however, due to the current code setup, the fix is actually just making sure that the data being processed by the checktime function is only the last item in the array... see below for the correction within the checktime function:
tempchar = MakeNum(x);
becomes
tempchar = MakeNum(x).split(' ').pop();

How to populate two texboxes using a javascript calendar control?

I need to populate the date time values in two textboxes at a same instant using a calendar control. Like on client side click of calendar control, the selected date in that control should get poulate on the corresponding textbox defined for say start date. There is an another textbox say enddate which also have to be populated with the same value on client click. Is there any third party javascript file to handle this scenario to populate two textboxes. Pls help me out on this?
Add this in ur page
<script language="JavaScript" src="calendardel.js"></script>
calendardel.js file code
// if two digit year input dates after this year considered 20 century.
var NUM_CENTYEAR = 30;
// is time input control required by default
var BUL_TIMECOMPONENT = false;
// are year scrolling buttons required by default
var BUL_YEARSCROLL = true;
var calendars = [];
var RE_NUM = /^\-?\d+$/;
function calendardel(obj_target) {
// assing methods
this.gen_date = cal_gen_date1;
this.gen_time = cal_gen_time1;
this.gen_tsmp = cal_gen_tsmp1;
this.prs_date = cal_prs_date1;
this.prs_time = cal_prs_time1;
this.prs_tsmp = cal_prs_tsmp1;
this.popupdel = cal_popup1del;
// validate input parameters
if (!obj_target)
return cal_error("Error calling the calendar: no target control specified");
if (obj_target.value == null)
return cal_error("Error calling the calendar: parameter specified is not valid target control");
this.target = obj_target;
this.time_comp = BUL_TIMECOMPONENT;
this.year_scroll = BUL_YEARSCROLL;
// register in global collections
this.id = calendars.length;
calendars[this.id] = this;
}
function cal_popup1del (str_datetime) {
this.dt_current = this.prs_tsmp(str_datetime ? str_datetime : this.target.value);
if (!this.dt_current) return;
var obj_calwindow = window.open(
'calendardel.html?datetime=' + this.dt_current.valueOf()+ '&id=' + this.id,
'Calendar', 'width=200,height='+(this.time_comp ? 265 : 230)+
',status=no,resizable=no,top=200,left=200,dependent=yes,alwaysRaised=yes'
);
obj_calwindow.opener = window;
obj_calwindow.focus();
}
// timestamp generating function
function cal_gen_tsmp1 (dt_datetime) {
return(this.gen_date(dt_datetime) + ' ' + this.gen_time(dt_datetime));
}
// date generating function
function cal_gen_date1 (dt_datetime) {
var ARR_MONTHS1 = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var month=ARR_MONTHS1[eval(dt_datetime.getMonth())]; //previous code in place of month=(dt_datetime.getMonth() < 9 ? '0' : '') +dt_datetime.getMonth() + 1
// alert(month);
return (
(dt_datetime.getDate() < 10 ? '0' : '') + dt_datetime.getDate() + "-"
+ (month) + "-"
+ dt_datetime.getFullYear()
);
}
// time generating function
function cal_gen_time1 (dt_datetime) {
return (
(dt_datetime.getHours() < 10 ? '0' : '') + dt_datetime.getHours() + ":"
+ (dt_datetime.getMinutes() < 10 ? '0' : '') + (dt_datetime.getMinutes()) + ":"
+ (dt_datetime.getSeconds() < 10 ? '0' : '') + (dt_datetime.getSeconds())
);
}
// timestamp parsing function
function cal_prs_tsmp1 (str_datetime) {
// if no parameter specified return current timestamp
if (!str_datetime)
return (new Date());
// if positive integer treat as milliseconds from epoch
if (RE_NUM.exec(str_datetime))
return new Date(str_datetime);
var arr_date=str_datetime.split('-');
if(arr_date.length!=3)
{
str_datetime="";
this.target.value="";
return new Date(str_datetime);
}
// else treat as date in string format
//=====================================================================\\
//=====================================================================\\
var arr_datetime = str_datetime.split(' ');
return this.prs_time(arr_datetime[1], this.prs_date(arr_datetime[0]));
}
// date parsing function
function cal_prs_date1del (str_dateField) {
//=====================================================================\\
//=====================================================================\\
str_date=str_dateField.value;
//alert(str_date);
//if not str_date field is a value======\\
if(!str_date)
str_date = str_dateField;
//=====================================================================\\
//=====================================================================\\
if(str_dateField.value=="")
return true;
var validmonth=false;
var Month=0;
var ARR_MONTH = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN","JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
var arr_date = str_date.split('-');
if(arr_date.length >3)
{
str_dateField.value = '';
str_dateField.focus();
alert("Invalid date format: '" + str_date + "'.\nFormat accepted is DD-MON-YYYY.");
return false;
}
//=====================================================================\\
//=====================================================================\\
//===========if date format is dd-mon-yyyy================================
if(arr_date.length == 3)
{
//=====================================================================\\
var mon=arr_date[1];
mon=mon.toUpperCase(mon);
for(i=0;i<ARR_MONTH.length;i++)
{
if(mon==ARR_MONTH[i])
{
Month=i+1;
validmonth=true;
break;
}
}
//=====================================================================\\
if (arr_date.length < 3)
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid date format: '" + str_date + "'.\nFormat accepted is DD-MON-YYYY.");
}
if (!arr_date[0])
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid date format: '" + str_date + "'.\nNo day of month value can be found.");
}
if (!RE_NUM.exec(arr_date[0]))
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid day of month value: '" + arr_date[0] + "'.\nAllowed values are unsigned integers.");
}
if (!arr_date[1])
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid date format: '" + str_date + "'.\nNo month value can be found.");
}
if (validmonth==false)
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid month value: '" + arr_date[1] + "'.\nAllowed values are month abbr..");
}
if (!arr_date[2])
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid date format: '" + str_date + "'.\nNo year value can be found.");
}
if (!RE_NUM.exec(arr_date[2]))
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid year value: '" + arr_date[2] + "'.\nAllowed values are unsigned integers.");
}
var dt_date = new Date();
dt_date.setDate(1);
if (Month < 1 || Month > 12) return cal_error ("Invalid month value: '" + arr_date[1] + "'.\nAllowed range is 01-12.");
dt_date.setMonth(Month-1);
if (arr_date[2] < 100) arr_date[2] = Number(arr_date[2]) + (arr_date[2] < NUM_CENTYEAR ? 2000 : 1900);
dt_date.setFullYear(arr_date[2]);
var dt_numdays = new Date(arr_date[2], Month, 0);
dt_date.setDate(arr_date[0]);
if (dt_date.getMonth() != (Month-1)) return cal_error ("Invalid day of month value: '" + arr_date[0] + "'.\nAllowed range is 01-"+dt_numdays.getDate()+".");
return (dt_date)
}
else //====date format is mon-yyyy or hh-yyyy or qq-yyyy or yyyy
{
if(arr_date.length == 1)
{
//check for year value only
if (!RE_NUM.exec(arr_date[0]))
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid year value: '" + arr_date[0] + "'.\nAllowed values are unsigned integers.");
}
}
else
{
if(arr_date[0].length == 3) //========check for month validity
{
//=====================================================================\\
var mon=arr_date[0];
mon=mon.toUpperCase(mon);
for(i=0;i<ARR_MONTH.length;i++)
{
if(mon==ARR_MONTH[i])
{
Month=i+1;
validmonth=true;
break;
}
}
//=====================================================================\\
if (validmonth==false)
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid month value: '" + arr_date[0] + "'.\nAllowed values are month abbr..");
}
//=====================================================================\\
}
else
{
//=========check for hh/qq
if(arr_date[0]== 'H2' || arr_date[0]== 'H1' || arr_date[0]== 'Q1' || arr_date[0]== 'Q2' || arr_date[0]== 'Q3' || arr_date[0]== 'Q4')
{
}
else
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid date format: '" + str_date + "'.\nFormat accepted is DD-MON-YYYY.");
}
}
//=====================================================================\\
//=====================================================================\\
}
}
}
// time parsing function
function cal_prs_time1 (str_time, dt_date) {
if (!dt_date) return null;
var arr_time = String(str_time ? str_time : '').split(':');
if (!arr_time[0]) dt_date.setHours(0);
else if (RE_NUM.exec(arr_time[0]))
if (arr_time[0] < 24) dt_date.setHours(arr_time[0]);
else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed range is 00-23.");
else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed values are unsigned integers.");
if (!arr_time[1]) dt_date.setMinutes(0);
else if (RE_NUM.exec(arr_time[1]))
if (arr_time[1] < 60) dt_date.setMinutes(arr_time[1]);
else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed range is 00-59.");
else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed values are unsigned integers.");
if (!arr_time[2]) dt_date.setSeconds(0);
else if (RE_NUM.exec(arr_time[2]))
if (arr_time[2] < 60) dt_date.setSeconds(arr_time[2]);
else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed range is 00-59.");
else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed values are unsigned integers.");
dt_date.setMilliseconds(0);
return dt_date;
}
function cal_error (str_message) {
alert (str_message);
return null;
}
then HTML code
<input name="dat" type="text" id="dat" size="11" maxlength="11" tabindex="1" value="">
<img src="img/cal.gif" alt="Click here to pick up the date" width="16" height="16" border="0" align="absmiddle">
and then add that script in script part
var cal1= new calendardel(document.forms['formname'].elements['dat']);
cal1.year_scroll = true;
cal1.time_comp = false;
You can use the OnChange event of the first input?
<script type="text/javascript">
function Text1OnChange() {
document.getElementById("Text2").value = document.getElementById("Text1").value;
}
</script>
<input id="Text1" type="text" onchange="Text1OnChange()"/>
<input id="Text2" type="text" />
Edit:
For asp TextBox, do not know if there is a better way, but it works.
<script type="text/javascript">
function <%= TextBox1.ClientID %>OnChange() {
document.getElementById("<%= TextBox2.ClientID %>").value = document.getElementById("<%= TextBox1.ClientID %>").value;
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
I could not put the js function name directly in the declaration of the textbox, it should change according to the id of the textbox, then put it in codebehind ...
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add("onchange", TextBox1.ClientID + "OnChange();");
}
other way:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<script type="text/javascript">
document.getElementById("<%= TextBox1.ClientID %>").onchange = function () {
document.getElementById("<%= TextBox2.ClientID %>").value = document.getElementById("<%= TextBox1.ClientID %>").value;
}
</script>

Categories