I have a kendo date picker which is set to format date as "MM/dd/yyyy". I want to check using jquery/javascript that if kendo date picker date must not be future date and date must be greater than '01/01/1900'.
The issue I am facing is when I take new date in script, it is like Date {Tue Jun 10 2014 11:17:48 GMT+0530 (India Standard Time)}. and my kendo date picker has value in 06/02/2012 format. I don't know how to compare it.
I know a method in kendo date picker named: parseFormats in which I have to give parsing format, but I don't know defualt date format of Javascript/Jquery and I don't know how to do it.
Kendo Date Picker
#(Html.Kendo().DatePickerFor(m => m.DateOfBirth).Format("MM/dd/yyyy").HtmlAttributes(new { style = "width:100%", Placeholder = "mm/dd/yyyy" }).Max(DateTime.Now.Date).Min(new DateTime(1900, 1, 2).Date))
You are getting the toString value of the new Date. Try this
var d = new Date(datepicker.value()); // looked at the docs, no obvious shortcut
if (d.getFullYear()<1900) alert("nope");
or
var now = new Date(), d = new Date(datepicker.value());
now.setHours(0,0,0,0); // normalise
if (d.getTime() > now.getTime()) alert("Please no future dates");
More information about JS Dates: MDN
You can also make it harder to select the invalid dates
$("#datetimepicker").kendoDateTimePicker({
value:new Date(),
min: new Date(1900,0,1), // JS months are 0 based!
max: new Date()
});
And lastly add the validation
$("#MyForm").kendoValidator({
rules: {
//implement your custom date validation
dateValidation: function (dateField) {
var currentDate = Date.parse($(dateField).val());
//Check if Date parse is successful
if (!currentDate) {
return false;
}
var now = new Date(), then=new Date(1900,0,1),d = new Date($(dateField).val());
now.setHours(0,0,0,0); // normalise
return d.getTime() >= then.getTime() && d.getTime() < now.getTime()
}
},
messages: {
//Define your custom validation massages
required: "Date is required message",
dateValidation: "Invalid date message"
}
});
Default Date Format of Javascript is MM/DD/YYYY
For Reference Follow Date Format
I would pretty much ignore Kendo's methods altogether and use moment.js in a validation function when you submit. You can format each date, min, max, and candidate, as YYYY-MM-DD, then compare using built-in .isAfter() and .diff() queries. Remember that you have to account for if they type something, not just pick it from the calendar, so you have to ensure you have 2-digit days. You also have to account for if someone enters in something outrageous that is higher than the Kendo control can deal with, like 1/1/0001 and 1/1/9000. Code below deals with that. You may also - though I did not include it here in my code, but did in my fiddle - want to account for if the year is only 2-digits, as well:
$('#btnValidate').click(function(){
var minDate = moment('1900-1-1');
var maxDate = moment(Date.parse(new Date()));
//var dateField = $("#datepicker").data("kendoDatePicker").value();
var dateField = $("#datepicker").val();
// Moment requires YYYY-MM-DD
dateField = dateField.replace('/','-').replace('/','-');
var year = dateField.split('-')[2];
var month = dateField.split('-')[0];
var day = dateField.split('-')[1];
if (month < 10 && month.toString().length == 1) { month = "0" + month; }
if (day < 10 && day.toString().length == 1) { day = "0" + day; }
dateField = year + '-' + month + '-' + day;
// Enter into moment and compare
var dateToConsider = moment(dateField);
var lowerLimitBreached = dateToConsider.diff(minDate) < 0;
var upperBoundBreached = dateToConsider.isAfter(maxDate);
alert('min: ' + moment(minDate).format('MM/DD/YYYY'));
alert('max: ' + moment(maxDate).format('MM/DD/YYYY'));
alert('our candidate: ' + moment(dateToConsider).format('MM/DD/YYYY'));
if(lowerLimitBreached || upperBoundBreached)
alert('Invalid date');
else
alert('Valid date');
});
http://jsfiddle.net/navyjax2/k5xx9xpu/
Note that the example doesn't show using times, but you could add that if you got the time from the .data("kendoDatePicker").value commented-out line. I just would not trust the year since "0001" will translate as "1901". So I would say that appending the time to the dateField object would be the way to go, and you can hard-code the time on it like moment(year + '-' + month + '-' + day + 'T' + hours + ':' + mins + ':' + secs + 'Z').utc() and the min like moment('1900-1-1T00:00:00Z'), though 00:00:00Z is already implied if you do not set it.
You can use KendoUI's datepicker method as shown below:
var datepicker = $("#datepicker").data("kendoDatePicker");
var value = datepicker.value();
Here value will be holding value like Tue Oct 11 2015 11:17:48 GMT+0530 (India Standard Time)
Now you can use simple condition to compare values
EDIT
You can refer demo at this fiddle
Once you have javascript date format you can use condition to compare dates, as I have in demo code
Related
I have 2 textboxes. One for Date and one for time.
.
I can set maxDate: new Date but that will ake it for every date I pick up from the calendar.
I also tried
$('#datetimepickerExample').datetimepicker({
format: 'LT', stepping: 1, autoclose: true,
onClose: function (selectedDate) {
$("#ContentPlaceHolder1_Event_Date_Txt").datepicker("option", "maxDate", selectedDate);
}
});
where "ContentPlaceHolder1_Event_Date_Txt" is the Date Textbox but it doesn't work. So when I pick an earlier date I can select all the 24 hours but when I select today it should limit me to the current time.
Before trying the method I've written below, I encourage you to read the plugin documentation here. I did not read whole documentation but I wanted to point out at least a direction for you.
1 - You should get current system date and time.
You can achieve that with JavaScript GetDate() Method
function getNow() {
var e = new Date,
month = e.getMonth() + 1,
date = e.getDate(),
year = e.getFullYear();
month < 10 && (month = "0" + month.toString()), date < 10 && (date = "0" + date.toString());
var currentTime = e.getHours() + ":" + e.getMinutes();
var currentDate = month + "/" + date + "/" + year;
//currentDate
//03/27/2021
//currentTime
//11:20
}
2 - If current date equals to the date you've picked you should limit the max time input to the current time. I believe you can achieve that with the code below. As I've said I did not read the documentation for the plugin you are using.
$("#ContentPlaceHolder1_Event_Date_Txt").datepicker({
onSelectDate:function(currentTime){
$('#datetimepickerExample').datetimepicker("option", "maxTime", currentTime);
}
});
Good Luck!
Here is a relatively simple function that solves this:
const isInThePast = date => {
const now = new Date()
if (typeof date !== typeof now) return "Invalid Date"
else return date < now ? true : false
}
You can call this function on every date change event and if it returns true, set the value, if it returns false give the user some sort of warning and keep the previous value.
var checkDate = new Date("22/22/2222");
When I check in IE 11 it convert to Wed Oct 22 00:00:00 EDT 2223 so my next line fails
if (checkDate != 'Invalid Date')
How to fix it?
As you've passed in an invalid date format (as far as the ECMA spec is concerned), the browser is free to choose to interpret it how it wishes. It seems IE thinks it can deal with it:
The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.16). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
If you're going to pass in strange formats, you're either going to need to validate them yourself or use a library that can do so better than the browsers can.
Months and days can "wrap" in JavaScript. One way to test if the date is legal is to see if the output date corresponds to the original input string. If it doesn't, then it wrapped.
function check(inputString) {
var checkDate = new Date(inputString);
// Get month, day, and year parts, assuming
// you don't have them already
var arr = inputString.split('/');
var isMonthWrapped = +arr[0] !== checkDate.getMonth() + 1;
var isDayWrapped = +arr[1] !== checkDate.getDate();
var isYearWrapped = +arr[2] !== checkDate.getFullYear();
console.log("Parts", +arr[0], +arr[1], +arr[2]);
console.log("Results", checkDate.getMonth() + 1, checkDate.getDate(), checkDate.getFullYear());
console.log("Wrapped?", isMonthWrapped, isDayWrapped, isYearWrapped);
var isLegal = checkDate !== 'Invalid Date' && !isMonthWrapped && !isDayWrapped && !isYearWrapped;
document.body.innerHTML += inputString + ': ' + (isLegal ? 'Legal' : 'Illegal') + '<br>';
};
check("22/22/2222");
check("12/12/2222");
I think that moment.js http://momentjs.com/ is a complete and good package about dates.
You could add string date and format.
moment("12/25/1995", "MM/DD/YYYY");
And you could check if date is valid.
moment("not a real date").isValid();
See documentation
http://momentjs.com/docs/#/parsing/string-format/
You should break up your string and parse Each date to integers individually. It will be much safer.
Do something like this
var dateString = "22/22/2222";
dateString.indexOf("/");
var day = parseInt(dateString.slice(0,dateString.indexOf("/")));
dateString = dateString.slice(1+dateString.indexOf("/"), dateString.length);
var month = parseInt(dateString.slice(0,dateString.indexOf("/")))
dateString = dateString.slice(1+dateString.indexOf("/"), dateString.length);
var year = parseInt(dateString);
console.log(day, month, year);
var date = new Date(0);
if(month>12) console.log("hey this is totally not a valid month maaaan!")
date.setDate(day);
date.setMonth(month);
date.setYear(year);
console.log(date);
I have to compare the date that they want to put in and the current date today, and if they have put in a date that is in the future, then alert them to change the date, otherwise insert the data.
Basically I am having issues comparing the dates. here is my code:
var today = year + '-' + month + '-' + day + ' 00:00:00';
var d1 = new Date(postdate); // postdate = 2014/02/01 ie: 1 Feb 2014
var d2 = new Date(today); // todays date
if(d1>d2){
alert('You cannot post in the future!');
}
But that doesnt seem to work. Where am I going wrong?
Convert the dates into a comparable number, like milliseconds.
if(d1.valueOf()>d2.valueOf()){
alert('You cannot post in the future!');
}
You don't need to create a new variable today.
If by today you are trying to get today's date, you can simply do
var today = new Date();
var d1 = new Date(postdate); // postdate = 2014/02/01 ie: 1 Feb 2014
//----------
var d2 = new Date(year,month,day); // todays date
//----------
if(d1>d2){
alert('You cannot post in the future!');
}
Remember month is 0 based index. So, for december it would be 11.
Compare the dates with the same format, if today is 2014-01-24 00:00:00 then postdate also should be 2014-02-01 00:00:00
Then use + prefix to compare milliseconds:
if(+d1 > +d2){
alert('You cannot post in the future!');
}
I have a date picker that generates a date like 6/30/2012 in a form field.
I need to convert this date to 2012-06-30 for mysql. I can get it close with the following.
var datePart=document.getElementById('formdate').value.split(/[^0-9]+/);
and then use to generate the date.
datePart2[2] + "-" + datePart2[1] + "-" + datePart2[0]
The problem is it gived me the date 2012-6-30 instead of 2012-06-30.
Is there an easier way to do this? Or a way to use my current method and ad a zero to the front of a digit if it is a single digit?
The Open Source date.js ( http://www.datejs.com/ )provides a really extensive framework for JavaScript dates, IMHO superior to the jQuery plug-in. It may be more than you need for this requirement, but I think it is a welcome addition to any JavaScript programmers's arsenal.
To format your example:
var mySqlDate = Date.parse('6/30/2012').toString('yyyy-MM-dd');
Are you using jQuery? if so you could use the Date Format plugin, makes date manipulation easy
http://archive.plugins.jquery.com/project/jquery-dateFormat
try this, hope this help:
Format date in jquery- from Sat Mar 03 2012 14:16:05 GMT+0530 to 03/03/2012
important you need to put a check condition like this one and if its less then 10 append 0 [code] date < 10 ? "0"+date : date; cheers!
something on the line of this:
function dateFormatFoo(){
var d = new Date();
date = d.getDate();
date = date < 10 ? "0"+date : date;
mon = d.getMonth()+1;
mon = mon < 10 ? "0"+mon : mon;
year = d.getFullYear()
return (date+"/"+mon+"/"+year);
}
Based on your example, a simple function is:
var formatUStoISOdate = (function() {
function aZ(n) {
return (n<10? '0' : '') + n;
}
var re = /[^0-9]/;
return function(d) {
var d = d.split(re);
return d[2] + '-' + aZ(d[0]) + '-' + aZ(d[1]);
// or
// return [d[2], aZ(d[0]), aZ(d[1])].join('-');
}
}());
alert(formatUStoISOdate('3/31/2011')); // 2011-03-31
I'm working on a mobile website and have drop down boxes for the Month, Date and Year. I'm needing something disallow them to continue to the next step if they chose a past date. I've seen calendar controls that do this but I'm not wanting to use a calendar control. I've spent the better part of the day looking for something but haven't been able to find anything. Does anyone have something like this or know of something that maybe I'm missing?
function date_check()
{
var trans_date = document.form1.selectmonth.options[document.form1.selectmonth.selectedIndex].value + "-" + document.form1.selectday.options[document.form1.selectday.selectedIndex].value + "-" + document.form1.selectyear[document.form1.selectyear.selectedIndex].value;
var d = new Date();
var today = (d.getMonth()+1) + "-" + d.getDate() + "-" + d.getFullYear();
if(new Date(trans_date) < new Date(today)){
alert("The shipping date cannot be in the past, please enter a valid shipping date.");
return false;
}
}
This is what I came up with but it's not working. Am I missing something else? I'll leave it selected as January 1 2011 and it doesnt throw the alert.
Simply get the selected values from the elements in question, concatenate the values with "-" or "/" and use the Date constructor to create a date object - compare that with the current date - if it is less than the current date, then fail.
// Inside your form's validation handler ...
var year, month, day, provided_date, now = new Date();
// Remove the hours, minutes and seconds from the now timestamp
now = new Date(now.getYear(), now.getMonth(), now.getDate());
// Get your year select - document.getElementById
// or any other method you have available
year = your_year_select.options[your_year_select.selectedIndex].value;
// and so on for month and day
// Remember, month is 0 indexed in JavaScript (January is month 0)
// so make sure your dropdown values take account of this.
// Otherwise, use month - 1 here.
provided_date = new Date(year, month, day);
// if all you need to do is validate the date
return provided_date >= now;
It sounds like you just need a validation function that creates a new date from the selected inputs and compares it to the current date. Something like:
function isFutureDate(year, month, day) {
return (Date.parse("" + year + "-" + month + "-" + day)) - new Date() > 0;
}
Except that you'll probably need to account for the timezone shift.