Using Javascript to roll back a date in a specific format - javascript

I'm not sure how to do this part, or even how to pose it as a question. I've been working on a project for my job in which we have a start date and an end date that the user enters either through a datepicker, or typing it in, within certain formatting requirements which then sends a query to our database to request information. The start and end date are auto-populated when the page loads, with the start date going back 14 days to give the user an auto two weeks information unless they wanted to get more/less. Here's the problem:
1: Both input boxes (html of course) were working, up until we hit October because it's a 2 digit month.
2: The rollback date of -14 gives a negative number instead of rolling back the date to September XX.
I've tried var StartDay = StartDate.setDate(StartDate.getDate() - 14); and all that gives is the date and time which SQL does not recognize. So I'm trying to figure out how to either:
1: Get it to roll back to the correct date which I can then populate the box with, or
2: Re-format the datetime given to a format that will be yyyy-mm-dd
So far I've spent all day searching for an answer and I've found multiple that are close but not quite all that I'm looking for.
$(function () {
$("#StartDate").datepicker({ dateFormat: "yy-mm-dd", changeMonth: true });
$("#EndDate").datepicker({ dateFormat: "yy-mm-dd", changeMonth: true });
var StartDate = new Date();
var StartDay = StartDate.setDate(StartDate.getDate() - 14);
var StartMonth = StartDate.getMonth() + 1;
var StartYear = StartDate.getFullYear();
//if (StartMonth < 10) StartMonth = "0" + Month;
//if (StartDay < 10) StartDay = "0" + StartDay;
var StartDateBox = StartDate;
var EndDate = new Date();
var EndDay = EndDate.getDate();
var EndMonth = EndDate.getMonth() + 1;
var EndYear = EndDate.getFullYear();
//alert('the new date is ' + EndDay);
if (EndMonth < 10) EndMonth = "0" + Month;
if (EndDay < 10) EndDay = "0" + EndDay;
var EndDateBox = EndYear + "-" + EndMonth + "-" + EndDay;
$("#StartDate").attr("value", StartDateBox);
$("#EndDate").attr("value", EndDateBox);
});
Everything labled "End" works fine. It's the rollback of 14 days that I'm having the issue with. I have the "if" commented out because the number is a negative and therefore crashes the function.
*edit Awesome! Much appreciated, now that I see it, it makes more sense. However, it's set to August, so it's missing the +1 after .getMonth. I'll try to figure that out.

I would make a function for formatting your dates, to reuse that code.
function formatDate(date) {
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
return year + "-" + month + "-" + day;
};
$(function () {
$("#StartDate").datepicker({ dateFormat: "yy-mm-dd", changeMonth: true });
$("#EndDate").datepicker({ dateFormat: "yy-mm-dd", changeMonth: true });
var StartDate = new Date();
StartDate.setDate(StartDate.getDate() - 14);
var StartDateBox = formatDate(StartDate);
var EndDate = new Date();
var EndDateBox = formatDate(EndDate);
$("#StartDate").attr("value", StartDateBox);
$("#EndDate").attr("value", EndDateBox);
});

Related

How to restrict previous and future date but can take five previous date and five future date in html5 date type

I want to restrict users from picking past and future dates but can pick five days of previous or future dates in html5 input type date.
I have used this to hide the previous date:
$(function() {
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
var day = dtToday.getDate();
var year = dtToday.getFullYear();
if(month < 10) {
month = '0' + month.toString();
}
if(day < 10) {
day = '0' + day.toString();
}
var maxDate = year + '-' + month + '-' + day;
$('#delivery_date').attr('min', maxDate);
});
You can use the min and max attributes in the input tag to restrict the range to only five days in the past and five days in the future.
Of course you'll need to get Today's date first using JS and dynamically set the min and max values.
Here is how you can get today's date using JS:
var today = new Date();
Here is how you can set the min and max attrubutes:
//assuming the date tag has the id date
var dateTag = document.getElementById("date");
var fiveDaysAgo = new Date(new Date().setDate(new Date().getDate() - 5)).toISOString().split("T")[0];
var fiveDaysInTheFuture = new Date(new Date().setDate(new Date().getDate() + 5)).toISOString().split("T")[0];
dateTag.setAttribute("min",fiveDaysAgo);
dateTag.setAttribute("max",fiveDaysInTheFuture);
Here is a complete version of it.
<!DOCTYPE html>
<html>
<body>
<input type="date" id="date" name="datemax">
</body>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var dateTag = document.getElementById("date");
var fiveDaysAgo = new Date(new Date().setDate(new Date().getDate() - 5)).toISOString().split("T")[0];
var fiveDaysInTheFuture = new Date(new Date().setDate(new Date().getDate() + 5)).toISOString().split("T")[0];
dateTag.setAttribute("min",fiveDaysAgo);
dateTag.setAttribute("max",fiveDaysInTheFuture);
});
</script>
</html>

A date field attached to a datepicker and html.validationmessagefor is not activating the validation script

I can't seem to find this answer. No one is using a combination of javascript, json, VS 2017, and vb.net. I have a date field on a web screen that has a date picker attached to it. I have all the coding for the date picker to work, but if the user manually changes the date field... the validator doesn't activate.
this is the code on my View:
<strong>Remark Date</strong>
#Html.ValidationMessageFor(Function(model) model.RemarkDate, "Remark date should be between 5 years in the past and 1 year in the future", New With {.onchange = "RemarkDate(this.value)"})
#Html.EditorFor(Function(model) model.RemarkDate)
This is the javascript in the view:
var today = new Date();
var yyyy = today.getFullYear();
var minYear = yyyy - 5;
var maxYear = yyyy + 1;
var yearsRange = minYear.toString() + ':' + maxYear.toString();
var startDate = minYear + today.getMonth() + 1 + today.getDate();
var endDate = maxYear + today.getMonth() + 1 + today.getDate();
$("#RemarkDate").datepicker({
minDate: "-0D -0M -5Y",
maxDate: "-0D -0M +1Y",
yearRange: yearsRange,
changeMonth: true,
changeYear: true,
"defaultDate": new Date(maxYear - 1, 1, 01),
});
$("#RemarkDate").datepicker("setDate", today);
$('#RemarkDate').blur(function () {
dte = $(this).val();
var userDate = new date(dte);
var inputDate = userDate.getFullYear() + userDate.getMonth() + 1 + userDate.getDate();
result = isValidDateRange(inputDate, startDate, endDate);
if (result === false) {
$("#RemarkDate").datepicker("setDate", today);
}
});
this is the controller after the "Save" button is pressed on the view
<HttpPost()>
<ValidateAntiForgeryToken()>
<HandleError(ExceptionType:=GetType(HttpAntiForgeryException), View:="AccessDenied")>
Public Function AddRemark(<Bind(Exclude:="memberRemark.Member,memberRemark.User")> MemberRemark As MemberRemark)
If ModelState.IsValid Then
MemberRemark.SecurityClassification = "FOUO" 'required by STIGs
db.MemberRemarks.Add(MemberRemark)
'if the user pressed the save button without changing any of the remark data, this blows up. Added a Try/Catch
'block so that it would skip over the error without crashing.
Try
db.SaveChanges()
Catch ex As Entity.Validation.DbEntityValidationException
ViewBag.ErrorMessage = "Remark Date or Remark Test or both are invalid"
End Try
End If
Return RedirectToAction("Details", New With {.id = MemberRemark.MemberID})
End Function

How to get days between date range by using javascript or jquery

In a form, I define a start date, an end date, and weekdays
Example:
Start date: 2017-02-07
End date: 2017-03-07
Weekdays: Monday and Thursday
Now I want to get all Mondays and Thursdays between start date and end date by using Javascript or jQuery.
Who can help me?
Thanks...
Simple code. Codepen
var startDate = new Date('2017-02-07');
var endDate = new Date('2017-02-17');
var monday = [];
var thursday = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
if(d.getDay()==1)
monday.push(d);
else if(d.getDay()==4)
thursday.push(d);
}
You can parse date and iterate over increment 1 day and getDay to map with sun(0) to sat(6)
var startDate = new Date("2017-02-07");
var endDate = new Date("2017-03-07");
var totalMon = [];
var totalThu = [];
for (var i = startDate; i <= endDate; ){
if (i.getDay() == 1){
totalMon.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
if (i.getDay() == 4){
totalThu.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
i.setTime(i.getTime() + 1000*60*60*24);
}
console.log(totalMon.length ,totalMon);
console.log(totalThu.length ,totalThu);
Below code finds number of Mondays. You can modify it to calculate any day. It basically finds the difference of days in two dates. Divide it by 7 (this is the number of times everyday will come). Now for pending days loop through the dates and check if a desired day comes in this loop.
var startDate = new Date(2017, 02, 07);
var endDate = new Date(2017, 03, 07);
var dayDiff = Math.round((endDate-startDate)/(1000*60*60*24));
var numberOfMondays = Math.floor(dayDiff/7);
var remainingDays = dayDiff%7;
for(i=0;i<remainingDays;i++)
{
var dateObj = new Date();
dateObj.setDate(endDate.getDate() - i);
if(dateObj.getDay() == 2)
numberOfMondays=numberOfMondays+1;
}
alert(numberOfMondays);
PS : the other two answer are looping through all the dates. I will not suggest this. In code above the number of iterations in loop will never exceed 6 irrespective of the difference in dates.

Full calendar: start calendar with a specific week

I'm using Full Calendar, I have a starting date and I need the calendar starts the week that corresponds to this date , I need to hide the previous weeks. here is a picture that explains my question.
in this example the starting date is April 20th.
$(".fc-day").each(function() {
var startDate = $('#start_date').val();
if (($(this).data('date')) < startDate){
$(this).parents().addClass('hidden');
}
});
I found a solution how to remove previous weeks, but I don't know how to replace them with future weeks.
This is the new script :
$(".fc-day").each(function() {
startDate = $('#start_date').val();
var date1 = new Date ($(this).data('date'));
var date2 = new Date (startDate);
var DD = date2.getDate();
var MM = date2.getMonth() + 1;
var YYYY = date2.getFullYear();
var startTraining = YYYY + '-'+ MM + '-'+ DD;
if ((date1 < date2) && (($(this).parent().get(0)) !== ($('.fc-day[data-date="' + startTraining + '"]').parent().get(0)))){
$(this).closest('.fc-row').addClass('hidden');
}
});
Fullcalendar automatically renders the week the date is in according to the firstDay property, so besides settings the correct day you also have to set the firstDay property to the correct day number by calling getDay().
element.fullCalendar({
defaultDate: startDate,
firstDay: startDate.getDay()
});

javascript date of specific day of the week in MM/dd/yyyy format not libraries

I know there are a lot of threads about finding the date of a specific day of the week in javascript but the all give it in the format like so:
Sun Dec 22 2013 16:39:49 GMT-0500 (EST)
but I would like it in this format 12/22/2013 -- MM/dd/yyyy
Also I want the most recent Sunday and the code I have been using does not work all the time. I think during the start of a new month it screws up.
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:0); // adjust when day is sunday
return new Date(d.setDate(diff));
}
I have code that gives me the correct format but that is of the current date:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
this prints:
>>> 12/23/2013
when I try to subtract numbers from the day it does not work, so I cannot get the dat of the most recent Sunday as MM/dd/yyyy
How do I get the date of the most recent sunday in MM/dd/yyyy to print, without using special libraries?
You can get the current weekday with .getDay, which returns a number between 0 (Sunday) and 6 (Saturday). So all you have to do is subtract that number from the date:
currentTime.setDate(currentTime.getDate() - currentTime.getDay());
Complete example:
var currentTime = new Date()
currentTime.setDate(currentTime.getDate() - currentTime.getDay());
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
console.log(month + "/" + day + "/" + year)
// 12/22/2013
To set the date to any other previous weekday, you have to compute the number of days to subtract explicitly:
function setToPreviousWeekday(date, weekday) {
var current_weekday = date.getDay();
// >= always gives you the previous day of the week
// > gives you the previous day of the week unless the current is that day
if (current_weekday >= weekday) {
current_weekday += 6;
}
date.setDate(date.getDate() - (current_weekday - weekday));
}
To get the date of next Sunday you have to compute the number of days to the next Sunday, which is 7 - currentTime.getDay(). So the code becomes:
currentTime.setDate(currentTime.getDate() + (7 - currentTime.getDay()));
Subtract days like this
// calculate days to subtract as per your need
var dateOffset = (24*60*60*1000) * 5; //5 days
var date = new Date();
date.setTime(date.getTime() - dateOffset);
var day = date.getDate() // prints 19
var month = date.getMonth() + 1
var year = date.getFullYear()
document.write(month + '/' + day + '/' + year);
Here is my suggestion. Create a function like so... in order to format any date you send it.
function formatDate(myDate) {
var tmp = myDate;
var month = tmp.getMonth() + 1;
var day = tmp.getDate();
var year = tmp.getFullYear();
return (month + "/" + day + "/" + year);
}
Now, to print the current date, you can use this code here:
var today = new Date();
var todayFormatted = formatDate(today);
To get the previous Sunday, you can use a while loop to subtract a day until you hit a Sunday, like this...
var prevSunday = today;
while (prevSunday.getDay() !== 0) {
prevSunday.setDate(prevSunday.getDate()-1);
}
var sundayFormatted = formatDate(prevSunday);
To see the whole thing together, take a look at this DEMO I've created...
** Note: Make sure you turn on the Console tab when viewing the demo. This way you can see the output.
You can create prototype functions on Date to do what you want:
Date.prototype.addDays = function (days) {
var d = new Date(this.valueOf());
d.setDate(d.getDate() + days);
return d;
}
Date.prototype.getMostRecentPastSunday = function () {
var d = new Date(this.valueOf());
return d.addDays(-d.getDay()); //Sunday is zero
}
Date.prototype.formatDate = function () {
var d = new Date(this.valueOf());
//format as you see fit
//http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
//using your approach...
var month = d.getMonth() + 1
var day = d.getDate()
var year = d.getFullYear()
return month + "/" + day + "/" + year;
}
console.log((new Date()).getMostRecentPastSunday().formatDate());
console.log((new Date("1/3/2014")).getMostRecentPastSunday().formatDate());
//or...
var d = new Date(); //whatever date you want...
console.log(d.getMostRecentPastSunday().formatDate());
Something like this will work. This creates a reusable dateHelper object (you will presumably be adding date helper methods since you don't want to use a library off the shelf). Takes in a date, validates that it is a date object, then calculates the previous Sunday by subtracting the number of millis between now and the previous Sunday.
The logging at the bottom shows you how this works for 100 days into the future.
var dateHelper = {
getPreviousSunday: function (date) {
var millisInADay = 86400000;
if (!date.getDate()) {
console.log("not a date: " + date);
return null;
}
date.setMilliseconds(date.getMilliseconds() - date.getDay() * millisInADay);
return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear();
}
}
var newDate = new Date();
console.log(dateHelper.getPreviousSunday(newDate));
var now = newDate.getTime();
for (var i=1; i<100; i++) {
var nextDate = new Date(now + i * 86400000);
console.log("Date: + " nextDate + " - previous sunday: " + dateHelper.getPreviousSunday(nextDate));
}

Categories

Resources