Use if statement with variables that are dynamic variables with Javascript - javascript

Basically I'm trying to create a validator for birthdays using the last information (mm/dd) but it is not returning the value as expected
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
today = mm + '/' + dd;
var newday = today.toString();
var birthday = "1992/09/21";
var monthday = birthday.substr(birthday.length - 5);
function validator(newday, birthday) {
if (monthday === newday) {
console.log('True');
return true;
}
else {
console.log('False');
return false
}
}
validator();
console.log(newday, monthday)

Can you try this
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
today = mm + '/' + dd;
var newday = today.toString();
console.log('New Date is', newday)
var birthday = "1992/09/21";
var monthday = birthday.substr(birthday.length - 5);
console.log('Month day', monthday)
function validator(newday, birthday) {
if (newday === birthday) {
console.log('True');
return true;
}
else {
console.log('False');
return false
}
}
validator(newday, monthday);
//console.log(newday, monthday)

momentjs is a light weight javascript library, used for
validating, manipulating and formatting date.
It provide wrappers to get month, year and date.
var date = new Date();
//Get todays Day and month in "DD/MM" format
var newday = moment(date, 'YYYY/DD/MM').format('DD/MM');
console.log("newDay: " + newday);
//Get birthdate Day and month in "DD/MM" format
var birthday = moment("1992/09/21", 'YYYY/MM/DD').format('DD/MM');
console.log("birthday: " + birthday);
function validator(newday, birthday) {
if (newday === birthday) {
console.log('True');
return true;
}
else {
console.log('False');
return false
}
}
validator(newday, birthday);
<script src="https://momentjs.com/downloads/moment.js"></script>
For more details you can visit moment.js page

Related

JQuery Doesn't Respond After Swal Alert

I am having a problem with my JQuery code, after swal alert, it doesn't append value to the inputs.
What I do first I check if the value of the start_date is Empty if yes then swal alert, then when I select it the values won't append to the boxes...
function ChangeDate() {
debugger;
var Startdate = document.getElementById("lease_stattdate").value;
var thisDate = new Date(Startdate);
var month = thisDate.getMonth();
var year = thisDate.getFullYear();
var dateSelected = thisDate.getUTCDate();
var firstDay = 1;
var LastDate = new Date(year, month + 1, 0);
var LastDay = LastDate.getDate();
var today = new Date();
var TodayMonth = today.getMonth();
var date = true;
if (month <= TodayMonth) {
jQuery.noConflict();
swal("Error!", "Please select upcoming month!", "warning");
$('#lease_stattdate').val('');
$('#renewal_notice').val('');
$('#end_date').val('');
$('#termination_notice').val('');
window.location.reload();
}
if (month > TodayMonth && dateSelected > firstDay) {
jQuery.noConflict();
swal("Error!", "Please select first day of the month!", "warning");
$('#lease_stattdate').val('');
$('#renewal_notice').val('');
$('#end_date').val('');
$('#termination_notice').val('');
window.location.reload();
}
if (month > TodayMonth && dateSelected == firstDay) {
var tempday = 15;
var nextdate = new Date(year, month + 23, tempday);
var NXmonth = nextdate.getMonth();
var NXyear = nextdate.getFullYear();
var terminateday = new Date(NXyear, NXmonth + 1, 0).getDate();
var exitdate = new Date(NXyear, NXmonth, terminateday).toLocaleDateString('en-ZA');
var renewalNotice = new Date(NXyear, NXmonth-2, 1).toLocaleDateString('en-ZA');
var terminationNotice = new Date(NXyear, NXmonth, 1).toLocaleDateString('en-ZA');
$('#renewal_notice').val(renewalNotice);
$('#end_date').val(exitdate);
$('#termination_notice').val(terminationNotice);
}
}

perform redirection if event time plus 4 hours is more than current time in js

There is a variable which contains event time. I want to redirect user if event time + 04:38 is more than current time.
Below is the code i have tried:
var deadline = getDayInstance("Monday","08:00:59")
function getDayInstance(day,time) {
const days = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,"Friday":5,"Saturday":6};
if(days[day]!==undefined)
var dayINeed = days[day];
else
var dayINeed = 2; // for Tuesday
const today = moment().tz("America/Los_Angeles").isoWeekday();
var dt;
// if we haven't yet passed the day of the week that I need:
if (today <= dayINeed) {
dt = moment().tz("America/Los_Angeles").isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
else {
dt = moment().tz("America/Los_Angeles").add(1, 'weeks').isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
console.log("Event Time: "+dt);
var maxLimit = Date.parse(moment(time,'HH:mm:ss').tz("America/Los_Angeles").add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
var now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit < now)
{
dt = moment().tz("America/Los_Angeles").add(1, 'weeks').isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
window.setVideo = false;
}
console.log(moment(time,'HH:mm:ss').tz("America/Los_Angeles").add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
console.log(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
return dt;
}
var maxLimit = Date.parse(moment(deadline,'YYYY-MM-DDTHH:mm:ss').add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
var now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit>=now){
var redirectTo = $("#lp-pom-button-673").attr('href');
if(redirectTo.length > 3){
window.location.href = redirectTo;
}
else{
window.location.href = "https://******/";
}
}
I need to maintain timezone in calculation.
I got the answer of this after refining the process theoretically and then try to implement it in JS. Below is the new code that can be used for this.
var deadline = getDayInstance("Tuesday", "02:32:00");
var maxLimit,now;
function getDayInstance(day,time) {
const days = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,
"Friday":5,"Saturday":6};
if(days[day]!==undefined)
var dayINeed = days[day];
else
var dayINeed = 2; // for Tuesday
const today = moment().tz("America/Los_Angeles").isoWeekday();
var dt;
// if we haven't yet passed the day of the week that I need:
if (today <= dayINeed) {
dt = moment().tz("America/Los_Angeles").isoWeekday(dayINeed)
.format('YYYY-MM-DD')+"T"+time;
}
else {
dt = moment().tz("America/Los_Angeles").add(1, 'weeks')
.isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
var d = new Date(dt);
d.setHours(d.getHours() + 4);
d.setMinutes(d.getMinutes() + 43);
d.setSeconds(d.getSeconds() + 32);
max = Date.parse(d);
now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit < now)
{
dt = moment().tz("America/Los_Angeles").add(1, 'weeks')
.isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
return dt;
}
if(maxLimit>=now){
var redirectTo = $("#lp-pom-button-673").attr('href');
if(redirectTo.length > 3){
window.location.href = redirectTo;
}
else{
window.location.href = "https://******/";
}
}

Javascript, advancing date range

I using a date-picker to set a start and end date. The date range is supposed to move forward each day for a two week, sliding window of entry.
My code below works but I would like to refactor it into something that is easier to maintain. What techniques or tools can I use to improve this code?
var challenge_start = new Date(2015,04,04);
var challenge_end = new Date(2015,06,12);
var range_start;
var range_end;
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(today<challenge_start) {
range_start=challenge_start;
range_end=challenge_start;
}
else if(today>challenge_start && today<challenge_end) {
if(mm==5) {
if(dd<18) {
range_start=challenge_start;
range_end=today;
}
else {
range_start=today.setDate(today.getDate()-14);
range_end=today;
}
}
else if(mm=6) {
if(dd<29) {
range_start=today.setDate(today.getDate()-14);
range_end=today;
}
else {
range_start=today.setDate(today.getDate()-14);
range_end=challenge_end;
}
}
else if(mm==7) {
if(dd<12) {
range_start=today.setDate(today.getDate()-14);
range_end=challenge_end;
}
else {
range_start=challenge_end;
range_end=challenge_end;
}
}
}
else if(today>challenge_end) {
range_start=challenge_end;
range_end=challenge_end;
}
$("#date").datepicker({
startDate: range_start,
endDate: range_end,
keyboardNavigation: false,
autoclose: true,
todayHighlight: true,
language: langdate,
disableTouchKeyboard: true
});
I may not understand what you are striving for, but I'm pretty sure you don't need to have those if(mm==x) and if(dd=x) statements.
Perhaps this is what you want:
var challenge_start = new Date(2015,04,04);
var challenge_end = new Date(2015,06,12);
function getDatePlusDays(origDate, days) {
var date = new Date(origDate.getTime());
date.setDate(date.getDate() + days);
return date;
}
function getClosestDateInRange(startDate, endDate, date) {
return (date < startDate) ? startDate
: ((date > endDate) ? endDate: date);
}
var today = new Date();
var range_start = getClosestDateInRange(challenge_start, challenge_end, getDatePlusDays(today, -14));
var range_end = getClosestDateInRange(challenge_start, challenge_end, today);
jsfiddle

how to autoselect current date in calendar control?

how to autoselect current date in javascript?.
I am using Calendar .js for displaying calendar,but dont know how to autoselect current date.Please guide me
Edit:
Calender.js
var oldLink = null;
// code to change the active stylesheet
function setActiveStyleSheet(link, title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
if (oldLink) oldLink.style.fontWeight = 'normal';
oldLink = link;
link.style.fontWeight = 'bold';
return false;
}
// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
cal.sel.value = date;
cal.sel.focus();
// just update the date in the input field.
// if ((cal.sel.id).substr(0,3) == "row" || cal.sel.id == "row3")
cal.callCloseHandler();
}
function closeHandler(cal) {
cal.hide(); // hide the calendar
}
function showCalendar(id, format) {
var el = document.getElementById(id);
if (calendar != null) {
// we already have some calendar created
calendar.hide();
// so we hide it first.
} else {
// first-time call, create the calendar.
var cal = new Calendar(false, null, selected, closeHandler);
// uncomment the following line to hide the week numbers
// cal.weekNumbers = false;
calendar = cal; // remember it in the global var
cal.setRange(1900, 2070); // min/max year allowed.
cal.create();
}
calendar.setDateFormat(format); // set the specified date format
calendar.parseDate(el.value); // try to parse the text in field
calendar.sel = el; // inform it what input field we use
calendar.showAtElement(el); // show the calendar below it
return false;
}
var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;
function isDisabled(date) {
var today = new Date();
return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}
function flatSelected(cal, date) {
var el = document.getElementById("preview");
el.innerHTML = date;
}
function showFlatCalendar() {
var parent = document.getElementById("display");
// construct a calendar giving only the "selected" handler.
var cal = new Calendar(false, null, flatSelected);
// hide week numbers
cal.weekNumbers = false;
// We want some dates to be disabled; see function isDisabled above
cal.setDisabledHandler(isDisabled);
cal.setDateFormat("DD, M d");
cal.create(parent);
cal.show();
}
function compareDate(date1, date2)
{
var strErrMsg = "";
tokens = date1.split("-");
dd = tokens[0];
mm = tokens[1];
mm=mm-1;
yyyy = tokens[2];
dt1 = new Date(yyyy,mm,dd);
tokens1 = date2.split("-");
dd = tokens1[0];
mm = tokens1[1];
mm=mm-1;
yyyy = tokens1[2];
dt2 = new Date(yyyy,mm,dd);
if(dt1.valueOf() <= dt2.valueOf())
alert(dt1);
alert(dt2);
var difInDays = (parseInt) ((dt2.getTime() - dt1.getTime())/(1000*60*60*24));
alert(difInDays);
if(dt1.valueOf() <= dt2.valueOf())
{
return strErrMsg;
}
else
{
strErrMsg = "Cannot be Greater than ";
return strErrMsg;
}
return strErrMsg;
}
function nextDateAfterThreeDays(date1)
{
tokens = date1.split("-");
dd = tokens[0];
mm = parseInt(tokens[1]-1);
yyyy = tokens[2];
dt1 = new Date(yyyy,mm,dd);
var time=dt1.getTime();
time=time;
dt1.setTime(time);
var newDD = dt1.getDate()+3;
var newMM = dt1.getMonth()+1;
var newYY = dt1.getFullYear();
if(newDD<10)
newDD="0"+newDD;
if(newMM<10)
newMM="0"+newMM;
date1=newDD+"-"+newMM+"-"+dt1.getFullYear();
return date1;
}
function compareBackDate(date1, date2)
{
var strErrMsg = "";
tokens = date1.split("-");
dd = tokens[0];
mm = parseInt(tokens[1])-1;
yyyy = tokens[2];
dt1 = new Date(yyyy,mm,dd);
tokens = date2.split("-");
dd = tokens[0];
mm = parseInt(tokens[1])-1;
yyyy = tokens[2];
dt2 = new Date(yyyy,mm,dd);
var difInDays = (parseInt) ((dt1.getTime() - dt2.getTime())/(1000*60*60*24));
alert(""+difInDays);
if(difInDays > 15 )
{
strErrMsg = " Should not be earlier six month than ";
}
return strErrMsg;
}
function convertDate(date1)
{
var tokens1;
var ddd;
var mmm="";
var mmm1;
var yyyyy;
var strErrMsg="";
tokens1 = date1.split("-");
ddd = tokens1[0];
mmm = tokens1[1];
yyyyy = tokens1[2];
if(mmm=="Jan")
{
mmm1=01;
}
if(mmm=="Feb")
{
mmm1=02;
}
if(mmm=="Mar")
{
mmm1=03;
}
if(mmm=="Apr")
{
mmm1=04;
}
if(mmm=="May")
{
mmm1=05;
}
if(mmm=="Jun")
{
mmm1=06;
}
if(mmm=="Jul")
{
mmm1=07;
}
if(mmm=="Aug")
{
mmm1=08;
}
if(mmm=="Sep")
{
mmm1=09;
}
if(mmm=="Oct")
{
mmm1=10;
}
if(mmm=="Nov")
{
mmm1=11;
}
if(mmm=="Dec")
{
mmm1=12;
}
strErrMsg=ddd+"-"+mmm1+"-"+yyyyy;
return strErrMsg;
}
function isComboSelected(objComboName)
{
var strErrMsg = "";
var objForm = document.getElementsByTagName("form")[0];
var objCombo = document.getElementsByName(objComboName)[0];
if(objCombo.options[0].selected == true)
{
strErrMsg = "Please Select Value.";
return strErrMsg;
}
return strErrMsg;
}
Edit2:
My code
<script type="text/javascript">
function submitFun()
{
var frm=document.forms[0];
var fromDate=frm.lsReqRecDate.value;
//var toDate=frm.toDate.value;
var date1=convertDate(fromDate);
//var date2=convertDate(toDate);
var mm;var dd;var yyyy;
var mm1;var dd1;var yyyy1;
var d1=date1;
var txtAppFrmDate=date1;
if(d1.indexOf("-")!=-1)
{
dd=d1.substring(0,d1.indexOf("-"));
mm=d1.substring(d1.indexOf("-")+1,d1.lastIndexOf("-"));
yyyy=d1.substring(d1.lastIndexOf("-")+1,d1.length);
}
start_Date=new Date(yyyy,mm-1,dd);
var fDate = txtAppFrmDate.split("-");
// var tDate = txtAppToDate.split("-");
var one_day=1000*60*60*24;
var fdt = new Date((fDate[2]),(fDate[1]-1),(fDate[0]));
frm.submit();
}
</script>
<html:form action="/exceptionNBReport.do" styleId="frmDatewise">
<TABLE class="ReportFilter">
<THEAD>
<TR>
<TD colspan="2">NB Report Search</TD>
</TR>
</THEAD>
</TABLE>
<br><br>
<TABLE class="ReportFilter">
<TR>
<TD class="lbl" align="left">Last requirement received date</TD>
<TD>
<html:text property="lsReqRecDate" style="width:170;" readonly="readonly"/>
<input type="reset" value="..." onclick="return showCalendar('lsReqRecDate','dd-MM-y');" name="reset"/>
</TD>
</TR>
<TR>
<TD colspan="2" align="center">
<html:button property="search" value="Submit" onclick="submitFun()"/>
</TD>
</TR>
</TABLE>
</html:form>
It would appear from the source code of Calendar that you need to pass the desired date into the Calendar() constructor as the second argument to the constructor. See lines 16 and 588 for details.

Date formatting options using Javascript

I have this code that updates a calendar widget and input field, while validating the date. We want the user to be able to input any type of m-d-y format (m.d.y, m-d-y, and so on). The problem is the YUI calendar widget only accepts the m/d/y format. All others it returns as NaN. I have tried a couple ways to format the date, but can't get anything that seems to work. I would like to be able to do this with out a lot of overblown code. Does anyone have any suggestions as to the best approach here? Here is my code:
//CALENDAR --------------------------------------------------------------------------------
var initCal = function(calendarContainer){
if(YAHOO.env.getVersion("calendar")){
var txtDate = Dom.get("dateOfLoss");
var myDate = new Date();
var day = myDate.getDate();
var month = myDate.getMonth() +1;
var year = myDate.getFullYear() -1;
var newDate = month + "/" + day + "/" + year;
function handleSelect(type, args, obj){
var dates = args[0];
var date = dates[0];
var year = date[0], month = date[1], day = date[2];
txtDate.value = month + "/" + day + "/" + year;
aCal.hide();
}
function updateCal(){
if (!(txtDate.value.match(/((\d{2})|(\d))\/|\-((\d{2})|(\d))\/|\-((\d{4})|(\d{2}))/))) {
alert("Enter date in mm/dd/yy or mm/dd/yyyy format.");
}
else {
if (txtDate.value != "") {
aCal.select(txtDate.value);
var selectedDates = aCal.getSelectedDates();
if (selectedDates.length > 0) {
var firstDate = selectedDates[0];
aCal.cfg.setProperty("pagedate", (firstDate.getMonth() + 1) + "/" + firstDate.getFullYear());
aCal.render();
}
else {
alert("Date of Loss must be within the past year.");
}
}
}
}
var aCal = new YAHOO.widget.Calendar(null, calendarContainer, {
mindate: newDate,
maxdate: new Date(),
title: "Select Date",
close: true
});
aCal.selectEvent.subscribe(handleSelect, aCal, true);
aCal.render();
Event.addListener("update", "click", updateCal);
Event.addListener(txtDate, "change", function(e){
updateCal();
});
// Listener to show the 1-up Calendar when the button is clicked
// Hide Calendar if we click anywhere in the document other than the calendar
Event.on(document, "click", function(e){
var el = Event.getTarget(e);
if(Dom.hasClass(el, "calendarButton"))
aCal.show();
else if (Dom.hasClass(el, "link-close") || !Dom.isAncestor(calendarContainer, el))
aCal.hide();
});
}
else {
var successHandler = function() {
initCal(calendarContainer);
};
OURPLACE.loadComponent("calendar", successHandler);
}
};
Did you tried http://www.datejs.com/?
Maybe you can define some patterns and test agaist the input.
How can I convert string to datetime with format specification in JavaScript?
var updateCal = function(){
if (!(txtDate.value.match(/^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.]\d\d+$/))) {
return;
}
//else if ((txtDate.value.match(/^(0?[1-9]|1[012])[- .](0?[1-9]|[12][0-9]|3[01])[- .]\d\d+$/))) {
//}
else {
var changedDate = txtDate.value;
changedDate = changedDate.replace(/[. -]/g, "/");
txtDate.value = changedDate;
badClaimDate = claimDateWithinPastYear();
aCal.select(changedDate);
I used a RegEx to determine which, if any, delimiters needed to be replaced and simply used .replace.

Categories