MVC Datetime picker validation - asp.net

I have an MVC application.My page contain two date time picker.start date and end date.My requirement is,
when anyone select the start date ,the end date should be calculated as start date +10 days.
also one condition, end date should not be less than start date.
How can i possible?
$(document).ready(function ()
{
$("#txtstartdate").datepicker
({
dateFormat: 'mm/dd/yy',
showAnim: "slideDown",
showOptions: {
origin: ["top", "left"]
}
});
$("#txtEnddate").datepicker
({
dateFormat: 'mm/dd/yy',
showAnim: "slideDown",
showOptions: {
origin: ["top", "left"]
}
});
});
I am using jquery datetime picker.
I just used javascript code but when I select the datetime picker it always showing prevoius selected date.how can I get selected date on selecting the datetime picker?

Try this:
$(function ()
{
$('#txtStartDate, #txtEndDate').datepicker(
{
showOn: "both",
beforeShow: customRange,
dateFormat: 'mm/dd/yy',
showAnim: "slideDown",
showOptions: {
origin: ["top", "left"]
},
firstDay: 1,
changeFirstDay: false
});
});
function customRange(input)
{
var min = new Date(2008, 11 - 1, 1); //the absolute minimum date
var dateMin = min;
var dateMax = null;
var dayRange = 10; //range of days
if (input.id == "txtStartDate")
{
if ($("#txtEndDate").datepicker("getDate") != null)
{
dateMax = $("#txtEndDate").datepicker("getDate");
dateMin = $("#txtEndDate").datepicker("getDate");
dateMin.setDate(dateMin.getDate() - dayRange);
if (dateMin < min)
{
dateMin = min;
}
}
else
{
dateMax = new Date(); //the absolute maximum date
}
}
else if (input.id == "txtEndDate")
{
dateMax = new Date(); //the absolute maximum date
if ($("#txtStartDate").datepicker("getDate") != null)
{
dateMin = $("#txtStartDate").datepicker("getDate");
var rangeMax = new Date(dateMin.getFullYear(), dateMin.getMonth(), dateMin.getDate() + dayRange);
if(rangeMax < dateMax)
{
dateMax = rangeMax;
}
}
}
return {
minDate: dateMin,
maxDate: dateMax,
};
}​
DEMO: http://jsfiddle.net/XdFpg/

Related

Google sheet + App Script : Rename every sheet if it meet criteria

Hi I'm using this script to rename every sheet by inserting 'Copy of' in front of the existing sheet name where the text in cell 'B36' = 'SAFETY ANALISIS' and the date from cell 'K3'is older then 30 days. My issue is having to do with the date I can't quite figure how to do it. Cell 'K3' cell are in this format "1-Aug-2021" I think I need to convert the date in 'K3' to a number format.
Any help would be greatly appreciated
function getSheet() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var sum = 0;
for (var i = 0; i < sheets.length ; i++ ) {
var sheet = sheets[i];
var date = new Date();
var ageInDays = 30;
var threshold = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() - ageInDays)
.getTime();
var val = sheet.getRange('K3').getValue();
var val2 = sheet.getRange('B36').getValue();
if (val >= threshold && val2 == 'SAFETY ANALYSIS') {
var sheetName = sheet.getName()
sheet.setName('Copy Of '+sheetName)
}
}
}
You may want to wrap the value you get from cell K3 in a Date() constructor. That should work with spreadsheet dates as well as text strings that look like dates.
I think you have the comparison in val >= threshold the wrong way around. Try something like this:
function renameOldSafetyAnalysisSheets() {
const timeLimit = 30 * 24 * 60 * 60 * 1000; // 30 days
const now = new Date();
const sheets = SpreadsheetApp.getActive().getSheets();
sheets.forEach(sheet => {
if (sheet.getRange('K3').getValue() !== 'SAFETY ANALYSIS') {
return;
}
const date = new Date(sheet.getRange('B36').getValue());
if (!date.getTime()
|| now.getTime() - date.getTime() < timeLimit) {
return;
}
try {
sheet.setName('Copy of ' + sheet.getName());
} catch (error) {
;
}
});
}
function getSheet() {
const shts = SpreadsheetApp.getActive().getSheets();
let d = new Date();
let ageInDays = 30;
let threshold = new Date(d.getFullYear(),d.getMonth(),d.getDate() - ageInDays).valueOf();
shts.forEach(sh => {
let val = new Date(sh.getRange('K3').getValue()).valueOf();
let val2 = sh.getRange('B36').getValue();
if (val <= threshold && val2 == 'SAFETY ANALYSIS') {
sh.setName('Copy Of ' + sh.getName())
}
});
}

Disable all weekends and specific days plus enable mothers day

I have the following code already working well in functions.php - I want to enable mothers day though (12 may 2019) which falls on a Sunday. How to do I add this to the return string?
function custom_adjust_datepicker_range () {
if ( is_checkout() ) {
?>
<script type="text/javascript">
var disabledDays = [
"1-1-2019","1-1-2020","2-1-2019","28-1-2019","27-1-2020","4-3-2019","2-3-2020","19-4-2019","10-4-2020","22-4-2019","13-4-2020","25-4-2019","25-4-2020","27-4-2020","3-6-2019","1-6-2019","30-9-2019","28-9-2020","25-12-2018","25-12-2019","25-12-2020","26-12-2018","26-12-2019","26-12-2020","27-12-2018"
];
jQuery( "#delivery_date" ).datepicker({
minDate: 2,
beforeShowDay: function(date) {
var day = date.getDay();
var string = jQuery.datepicker.formatDate('d-m-yy', date);
var isDisabled = (jQuery.inArray(string, disabledDays) != -1);
return [(day != 1 && day != 0 && !isDisabled), ''];
}
});
</script>
<?php
}
} // End custom_adjust_datepicker_range()
add_action( 'wp_footer', 'custom_adjust_datepicker_range', 50 );
Consider the following example.
jQuery(function() {
var disabledDays = [
"1-1-2019", "1-1-2020", "2-1-2019", "28-1-2019", "27-1-2020", "4-3-2019", "2-3-2020", "19-4-2019", "10-4-2020", "22-4-2019", "13-4-2020", "25-4-2019", "25-4-2020", "27-4-2020", "3-6-2019", "1-6-2019", "30-9-2019", "28-9-2020", "25-12-2018", "25-12-2019", "25-12-2020", "26-12-2018", "26-12-2019", "26-12-2020", "27-12-2018"
];
var dtf = 'd-m-yy';
function getMothersDay(y) {
var mayFirst = new Date(y, 4, 1);
var dayOfWeek = mayFirst.getUTCDay();
var firstSunday;
if (dayOfWeek == 0) {
firstSunday = mayFirst;
} else {
firstSunday = new Date(y, 4, 1 + (7 - dayOfWeek));
}
var mothersDay = new Date(y, 4, firstSunday.getDate() + 7);
return mothersDay;
}
function isMothersDay(dt) {
return (jQuery.datepicker.formatDate(dtf, dt) == jQuery.datepicker.formatDate(dtf, getMothersDay(dt.getFullYear())));
}
jQuery("#delivery_date").datepicker({
minDate: 2,
beforeShowDay: function(date) {
var day = date.getDay();
var string = jQuery.datepicker.formatDate(dtf, date);
var isDisabled = jQuery.inArray(string, disabledDays);
var result = [
true,
"",
""
];
switch (true) {
case isMothersDay(date):
// Mother's Day
result = [
true,
"mothers-day",
"Mother's Day"
];
break;
case (isDisabled >= 0):
// Disable Days
result[0] = false;
break;
case (day == 0):
case (day == 6):
// Weekends
result[0] = false;
break;
}
return result;
}
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>Delivery Date: <input type="text" id="delivery_date"></p>
See More: How to calculate Mother’s Day in JavaScript
This example was based on first Google search result I performed. In the future, you may want to search for basic examples.
This is not adjusted for WordPress, so you will need to adapt the code to your needs.
You have 3 basic checks:
Is the date Mother's Day
Is the date in the array of dates
Is the date a weekend day
You might have other scenarios arise so using a switch() might be easier overall. I move from the least common condition to the most common condition. You could add more and only check if it's Mother's Day if the month is May and they day of the month is within the first 2 weeks: (date.getMonth() == 4 && date.getDate() < 15).
Hope this helps.

Full Calendar - How get year and month after click on prev or next button?

I use Full Calendar in my project and I need to get year and month when I click on Prev or Next button.
This is my code, but doesn't work !! It return alway the current date.
$('body').on('click', 'button.fc-prev-button', function () {
var tglCurrent = $('#calendar').fullCalendar('getDate');
var year = moment(tglCurrent).format('YYYY');
var month = moment(tglCurrent).format('MM');
alert('Year is '+year+' Month is '+month);
});
$('body').on('click', 'button.fc-next-button', function () {
var tglCurrent = $('#calendar').fullCalendar('getDate');
var year = moment(tglCurrent).format('YYYY');
var month = moment(tglCurrent).format('MM');
alert('Year is ' + year + ' Month is ' + month);
});
How can I resolve this issue ?
Try to do it in below way
$('body').on('click', 'button.fc-prev-button', function () {
var tglCurrent = $('#calendar').fullCalendar('getDate');
var date = new Date(tglCurrent);
var year = date.getYear();
var month = date.getMonth();
alert('Year is '+year+' Month is '+month);
});

Asp.net webform with flot.js chart on return Json does not work

I am using ASP.NET webforms for flot charts I connected to database in test.aspx.cs file using [Webmethod] where I can return json.
I stored the return value both in textarea and $.plot(placeholder, [and also here], options) It does not print the graph in placeholder however when I do:
var data = past
the value of textarea here and run applicationn it prints to me the value.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<string> GetLocation(string location)
{
List<string> result = new List<string>();
StringBuilder strQuery = new StringBuilder();
strQuery.Append("SELECT Location.Nome_Location, DATEPART(day, Statistiche.Data_Statistica) AS SDay, COUNT(Statistiche.ID_Tabella) AS Stats");
strQuery.Append(" FROM Statistiche INNER JOIN Tabelle ON Statistiche.ID_Tabella = Tabelle.ID_Tabella INNER JOIN");
strQuery.Append(" Location ON Statistiche.ID_Colonna_Statistica = Location.ID_Location");
strQuery.Append(" WHERE (Statistiche.ID_Tabella = 2) AND (Statistiche.ID_Box = 60) AND (Location.Nome_Location = 'Albilò')");
strQuery.Append("GROUP BY Location.Nome_Location, DATEPART(day, Statistiche.Data_Statistica)");
string query = strQuery.ToString();
SqlConnection con = new SqlConnection("");
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
int counter = 1;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (counter == 1)
{
result.Add("[{'label': 'Europe (EU27)','data':[[" + dr["SDay"].ToString() + "," + dr["Stats"].ToString() + "]");
}
else
result.Add("[" + dr["SDay"].ToString() + "," + dr["Stats"].ToString() + "]");
if (counter==31)
{
result.Add("[" + dr["SDay"].ToString() + "," + dr["Stats"].ToString() + "]]}]");
}
counter++;
}
return result;
}
$.ajax({
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "test.aspx/GetLocation",
data: "{'location':'Albilò'}",
success: function drawChart(msg) {
var options = { lines: { show: true }, points: { show: true }, xaxis: { tickDecimals: 0, tickSize: 1} };
var ddata = [];
var data = msg.d;
for (var i = 0; i < 32; i++) {
ddata.push(data[i]);
}
var placeholder = $("#placeholder");
$("#txtvalue").val(ddata);
var datad = $("#txtvalue").text();
$.plot(placeholder, ddata, options);
},
error: function () {
alert("call is called111");
}
});
First of all, why do you create JSON yourself? You've already specified to return JSON in you attributes.
Refactore method to return simple array of POCO objects like
[Serializable]
public class pocoObject
{
public string Label;
..
}
Then your method should just return list of object and have attributes set up:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<pocoObject> GetLocation(string location)
{
...
return result; // result is list of pocoObjects
}
Flot.js is rather sensitive to data you set as source, so after this take a look at data in firebug, it should be correct json formatted data. So please visit wiki and also compare your data to working samples.
This how you can initiliaze legend names of you plot:
$(function () {
var d1 = [];
for (var i = 0; i < Math.PI * 2; i += 0.25)
d1.push([i, Math.sin(i)]);
var d2 = [];
for (var i = 0; i < Math.PI * 2; i += 0.25)
d2.push([i, Math.cos(i)]);
var d3 = [];
for (var i = 0; i < Math.PI * 2; i += 0.1)
d3.push([i, Math.tan(i)]);
$.plot($("#placeholder"), [
{ label: "sin(x)", data: d1},
{ label: "cos(x)", data: d2},
{ label: "tan(x)", data: d3}
], {
series: {
lines: { show: true },
points: { show: true }
},
xaxis: {
ticks: [0, [Math.PI/2, "\u03c0/2"], [Math.PI, "\u03c0"], [Math.PI * 3/2, "3\u03c0/2"], [Math.PI * 2, "2\u03c0"]]
},
yaxis: {
ticks: 10,
min: -2,
max: 2
},
grid: {
backgroundColor: { colors: ["#fff", "#eee"] }
}
});
});

Verify a date in JavaScript

I need to do user validation of a date field, it should be in the format yyyyMMdd and should not be more than one year in the future. How would I go about doing this? Currently I only have a crude regexp which is insufficient.
function VerifyDate(source, args)
{
var regexp = /^([1-2]{1}[0-9]{1})\d{2}([0][1-9]|[1][0-2])([0][1-9]|[1-2][0-9]|[3][0-1])$/
var result = args.Value.match(regexp);
if(result) {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
Take the regex to check the format only. You can stay simple:
^(\d{4})(\d{2})(\d{2})$
Then parse the date and check the range:
function VerifyDate(source, args)
{
args.IsValid = false;
var regexp = /^(\d{4})(\d{2})(\d{2})$/;
var daysInMonth = function (y, m) {return 32-new Date(y, m, 32).getDate(); };
var ma = regexp.exec(args.Value);
if (ma && ma.length == 4 && ma[2] < 12 && ma[3] <= daysInMonth(ma[1], ma[2]))
{
var diff = new Date(ma[1], ma[2], ma[3]) - new Date();
args.IsValid = diff < 31536000000; // one year = 1000ms*60*60*24*365
}
}
new Date() don't throw an exception if month or day is out of range. It uses the internal MakeDay to calculate a date (see ECMAScript Language Specification section 15.9.3.1 and 15.9.1.13). To make sure that the date is valid in the function below, the input is converted to integers who is converted to a date, and then the parts of the date are compared to the integers.
Since date uses MakeDay, the calculation of maxDate works even if now is the leep day (xxxx0229 will be yyyy0301 where yyyy=xxxx+1)
function verifyDate(args)
{
var result=false,
match = args.Value.match(/^(\d{4})(\d{2})(\d{2})$/);
if (match && match.length === 4)
{
var year = parseInt(match[1],10),
month =parseInt(match[2],10) -1, // 0 = January
day = parseInt(match[3],10),
testDate= new Date(year,month,day),
now = new Date(),
maxDate = new Date(now.getFullYear() + 1, now.getMonth(), now. getDate()),
minDate = new Date(1800,0,1),
result = (
testDate.getFullYear() === year &&
testDate.getMonth() === month &&
testDate.getDate() === day &&
testDate >= minDate &&
testDate <= maxDate
);
}
args.IsValue = result;
return result;
}
The solution I finally went with is a combination of your answers, I used datejs which seems pretty nice. Here is my final validation function. For some reason the month seems to use a 0 based index so that's why it says -1 in the .set().
function VerifyDate(source, args)
{
args.IsValid = false;
var regexp = /^(\d{4})(\d{2})(\d{2})$/;
var m = regexp.exec(args.Value);
if (m && m.length == 4) {
try {
var result = Date.today().set({ year: Number(m[1]), month: Number(m[2]-1), day: Number(m[3]) });
if (result < Date.today().add({ years: 1 })) {
args.IsValid = true;
}
}
catch (ex) {
}
}
}

Resources