Javascript, advancing date range - javascript

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

Related

Use if statement with variables that are dynamic variables with 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

How to target bootstrap datepicker's its own '.datepicker-dropdown' when there is multiple datepickers in a page.?(without container option)

In my project - which is a App, I have multiple datepicker which is Version 2.0. My Client wants me to customise my datepicker by showing the date of the calendar top, so I did some tweaks, it is working on the page with one datepicker but it's an another story when it comes to multiple datepicekers on one page.my code is as follows.
$(elem).datepicker(options);
//Customized Datepicker Plugin 03/07/2017
//Author - Jithin Raj
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
$(elem).on('show', function() {
var cPicVal = '',
yPicVal = '';
if ($('.datepicker-dropdown').find('.new-date-wrap').length <= 0) {
$('.datepicker-dropdown').prepend('<div class="new-date-wrap"><div class="custom-year-pic-view"><span></span></div><div class="custom-day-pic-view"><span></span></div></div>');
}
if ($(elem).val() == '') {
cPicVal = (Date.parse(today).toString('ddd, MMM dd'));
yPicVal = (Date.parse(today).toString('yyyy'));
} else {
cPicVal = (Date.parse($(elem).val()).toString('ddd, MMM dd'));
yPicVal = (Date.parse($(elem).val()).toString('yyyy'));
}
$('.custom-day-pic-view').find('span').text(cPicVal);
$('.custom-year-pic-view').find('span').text(yPicVal);
});
});
Can anyone suggest me a another fullprofe method, thankyou Cheers..
I think I found an answer.
I changed my code a little bit and added moment.js and now it's working all over my app.
$(elem).datepicker(options);
//Customized Datepicker Plugin 03/07/2017
//Author - Jithin Raj
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
$(elem).on('show', function() {
var cPicVal = '',
yPicVal = '';
elem = $(this)
if ($('.datepicker-dropdown').find('.new-date-wrap').length <= 0) {
$('.datepicker-dropdown').prepend('<div class="row-fluid new-date-wrap"><div class="row-fluid custom-year-pic-view"><span></span></div><div class="row-fluid custom-day-pic-view"><span></span></div></div>');
}
if ($(elem).val() == '') {
cPicVal = (moment(today).format('ddd, MMM DD'));
yPicVal = (moment(today).format('YYYY'));
} else {
cPicVal = (moment($(elem).val()).format('ddd, MMM DD'));
yPicVal = (moment($(elem).val()).format('YYYY'));
}
$('.custom-day-pic-view').find('span').text(cPicVal);
$('.custom-year-pic-view').find('span').text(yPicVal);
});

Check if a HTML has loaded into a DIV

I want to be able to set up HTML pages and load them into a single home page. Each html file will be named as the date (eg 03052016.html for today) and then the correct html will be pulled in each day on the homepage.
However not all days will have a html file, in which case it should roll back to a previous day. I have successfully loaded the page, nice and easy but can't work out a way to identify that the page hasn't loaded and subtract one from the day. My current attempt is the following:
<body>
<div id="success"></div>
<script>
//section creates the html file name for today
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 = dd+mm+yyyy+'.html';
var today = "05052016.html";
//do loop to subtract days until file is found
do{
var found = true; //variable records file presence
$( "#success" ).load( today, function( response, status, xhr ) {
if ( status == "error" ) {
var found = false;
if(parseInt(dd)>1){
dd = parseInt(dd)-1;
}else {
mm = parseInt(mm)-1;
dd = 30 //will deal with 31/30/28 day months later.
}
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = dd+mm+yyyy+'.html';
//
console.log( msg + xhr.status + " " + xhr.statusText );
}
});
}until(found == false )
</script>
I am new to web authoring so please be brutal if I am way off how to implement this. It seems so easy but the loop just won't work!
I am currently testing in FireFox, and using jquery-1.10.2.js
check de length of the content of the quuestioned div.
var div = $('div');
var dHtml = div.html();
var long = dHtml.length;
if(long > 0)
{
//do stuff
}
You need to understand that ajax (which is behind load) is asynchronous so you cannot test the found outside the success.
Try this:
function pad(num) {return String("0"+num).slice(-2)}
function getFilename(date)
var dd = pad(date.getDate());
var mm = pad(date.getMonth()+1); //January is 0!
var yyyy = date.getFullYear();
return ""+dd+mm+yyyy+".html";
}
var date = new Date(),
aDay = 10*24*60*60*1000,
giveUp = new Date(date.getTime()-(10*aDay)); // max 10 days back
function loadFile(date) {
$("#success").load( getFilename(date), function() {
if (status == "error") {
if (date>giveUp) {
date.setDate(date.getDate()-1)
loadFile(date);
}
}
});
}
$(function() {
loadFile(date);
});

Bootstrap Date picker

Hey this question might have been asked before, however I haven't been able to find a solution.
I have two bootstrap date pickers. Based on the first date selection the second date should be restricted to the first date + 15.
I would like the vice-versa to happen as well. When a user selects the second date first the first date should be restricted to the second date - 15.
My code so far :
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('#inputDate1').datepicker({
onRender: function (date) {
return date.valueOf() > now.valueOf() ? 'disabled' : '';
}
}).on('changeDate', function (ev) {
//made changes to condition below
var newDate = new Date(ev.date)
checkout.setValue(newDate);
checkin.hide();
$('#inputDate2')[0].focus();
}).data('datepicker');
var checkout = $('#inputDate2').datepicker({
onRender: function (date) {
//made changes to below line
var after = new Date(checkin.date);
after.setDate(after.getDate() + 14);
if(now.valueOf() > after.valueOf())
{
return (date.valueOf() <= after.valueOf()) && (date.valueOf()>= checkin.date.valueOf()) ? '' : 'disabled';
}
else if(after.valueOf() > now.valueOf())
{
return (date.valueOf() <= now.valueOf()) && (date.valueOf()>= checkin.date.valueOf()) ? '' : 'disabled';
}
}
}).on('changeDate', function (ev) {
checkout.hide();
}).data('datepicker');
Any help is appreciated.
Ok i figured out how to do it and here i paste my working code.
$(document).ready(function() {
var nowTemp = new Date();
var end = new Date();
var start;
$('#start').datepicker({
startDate: start,
endDate: end,
autoclose: true
}).on('changeDate', function (e){
var tempdate = new Date(e.date);
var tempdate1 = new Date(e.date);
tempdate1.setDate(tempdate1.getDate() + 15);
$('#end').datepicker('setStartDate', tempdate);
$('#end').datepicker('setEndDate', tempdate1);
});
$('#end').datepicker({
startDate: start,
endDate: end,
autoclose: true
}).on('changeDate', function (e){
var tempdate = new Date(e.date);
var tempdate1 = new Date(e.date);
tempdate1.setDate(tempdate1.getDate() - 15);
$('#start').datepicker('setStartDate', tempdate1);
$('#start').datepicker('setEndDate', tempdate);
});
});

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