How to validate user input is current date and time? - javascript

In html i use ext.net datefield
<ext:DateField runat="server" ID = "date" Format="Y-m-d hh:mm:ss" SubmitFormat="Y-m-d H:i:s" MarginSpec="0 0 0 60" FieldLabel="Gate In Date/Time" AllowBlank="false" IndicatorText="*" IndicatorCls="red-text"/>
when it view it shows correct date but the time is always 12:00:00.In javascript
i do it like this
var iframeID = $('iframe').attr('id');
var myDate = lazyMethod_get(iframeID, "formdetail", "date")
var today = new Date().toISOString().slice(0, 10);
alert(myDate);
alert(today);
if (myDate > today) {
alert("Entered date is greater than today's date ");
}
else {
alert("Entered date is less than today's date ");
}}
the validation always alert the date entered less than today date. I just want to validate the date and time if the user insert for example 2016-02-03 the date is wrong and get current date.
Thank you.

Time in microseconds.
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
Do your formatting after you do your calculations.
What is your lazyMethod_get() workings. Is it returning a string, or a Date object.

When you do:
new Date().toISOString().slice(0, 10);
toISOString generates a UTC date (i.e. the time zone offset is 00:00) so it may be a different date from the host system.
E.g. for a user in time zone +10:00 when it is 09:30 on 25 May, the above will return a date string for 24 May. Similarly, for systems where the offset is west of Greenwich, dates will be one day later for times in the evening (e.g. 20:30 on 25 May in time zone -04:00 will be 00:30 on 26 May UTC).

First - The Ext.NET DateField only returns a date (MM-dd-yyyy) not a time. The time always defaults to 12:00:00.
I would compare the year, day, and month of each.
javascript:
var isToday = function (field) {
var fieldDate = field.getValue();
var today = new Date()
if ((today.getFullYear() + today.getMonth() + today.getDate())
== (fieldDate.getFullYear() + fieldDate.getMonth() + fieldDate.getDate())) {
return true;
}
else {
return false;
}
}
Markup:
<ext:DateField ID="DateField1" runat="server">
<Listeners>
<Select Handler="alert( isToday(#{DateField1}) )" />
</Listeners>
</ext:DateField>

Related

Comparing time from different timezones with moment.js

I have a Node.js server that triggers function based on timezones. Specifically, I'm using moment-timezone and from a fixed date and time input I need to trigger action at that same input but in different time zones.
So if I set in my server that the action should be triggered at 1:00 pm UK time and the user is in New York, I want the action to be triggered at 1:00 pm in New York.
That's what I am doing now:
exports.time_to_trigger = function(hour, date) {
var user_timezone = "Asia/Tokyo";
// create date object from date + hour strings
var dateObj = moment(date + hour, process.env.DATE_FORMAT + " HH:mm a");
// create offset
var max_value = moment(dateObj).add(3, 'minutes');
var low_value = moment(dateObj).add(-3, 'minutes');
console.log(max_value); // -> moment("2018-01-25T13:03:00.000")
console.log(low_value); // -> moment("2018-01-25T12:57:00.000")
// get the now value of the user timezone
var user_now = moment.tz(moment(), user_timezone);
console.log(user_now); // -> moment.parseZone("2018-01-24T13:01:00.038+09:00")
console.log(user_now.isAfter(low_value)); // -> false
console.log(user_now.isBefore(max_value)); // -> true
return (
user_now.isAfter(low_value) &&
user_now.isBefore(max_value)
)
}
As you can see from the comment, this is not working as the comparison with isAfter and isBefore take into consideration the time zone that I converted on purpose not to have this problem. How can I solve this?
Your issue is that you use timezone to get user_now but not to create dateObj. So dateObj is missing the timezone offset and your 2 dates are not comparable as you would wish.
To have all your dates on the same timezone:
// create date object from date + hour strings
var dateObj = moment.tz(date + hour, process.env.DATE_FORMAT + " HH:mm a", user_timezone);

Can not compare date using Angular.js/Javascript

I have an issue. I can not compare todays date with previous date using Angular.js/Javascript. I am explaining my code below.
var today=new Date();
if(today >= new Date($scope.date1.split("-").reverse().join(","))){
alert('Please select todays date or upcoming date');
}
Here i am getting $scope.date1 value like this 2016-10-18 format.Here i could not compare while date is 2016-10-18 .Here i need while selected date is previous date of todays date that alert will display.Please help me.
new Date($scope.date1.split("-").reverse().join(",")) will not create a valid date.
//Pass the string directly
var nDate = new Date('2016-10-18');
var today = new Date();
if (today >= nDate) {
console.log('Please select todays date or upcoming date');
}
You cannot compare dates as you are doing.
When you initialize date object with new Date(), it is set with current time.
So
var today = new Date("2016-10-19"); //----> current date here
var anothertoday = new Date();
shall never be the same
anothertoday > today //-----> true
The above expression evaluates to true because if you see the time of both the dates
today.getHours() //---> 0
anothertoday.getHours() //---> current time shall be displayed
To compare it on the basis of only date you need to set time of anothertoday to 0 by anothertoday.setHours(0,0,0,0)
Now the above expression should evaluate to false
anothertoday > today //---->false
So in your case your code should be similar to this
var today = new Date();
$scope.date1 = "2016-10-18";
$scope.datearr = $scope.date1.split("-");
var yesterday = new Date($scope.datearr[0],$scope.datearr[1] - 1,$scope.datearr[2]);
today.setHours(0,0,0,0); //----> set time to 0 hours
if(today > yesterday)
console.log("Please select todays date or upcoming date");

JavaScript simple date validation

I try to validate a date entered by the user. It must be today or a later date. How I can do that?
Why the condition in the code below is false?
var today = new Date();
var idate = new Date('02/09/2014');
if(today > idate) {
alert('your date is big');
}
If I set today then it is today's date and also I pass in idate then it is also today's date then how can I compare dates?
Here is JSFiddle: http://jsfiddle.net/0osh0q8a/1/
A few things to consider.
When you're creating a new Date object from a string representation, do it in the format YYYY-MM-DD. This will avoid problems with locale.
When comparing two dates, if the time can be ignored, set both to the exactly same time. It looks to be the case here.
Finally, use Date.parse() to make sure your object is a valid date and make it possible to be compared.
var today = new Date();
var idate = new Date('2014-09-02');
// The date entered by the user will have the same
// time from today's date object.
idate.setHours(today.getHours());
idate.setMinutes(today.getMinutes());
idate.setSeconds(today.getSeconds());
idate.setMilliseconds(today.getMilliseconds());
// Parsing the date objects.
today = Date.parse(today);
idate = Date.parse(idate);
// Comparisons.
if (idate == today) {
alert('Date is today.');
}
else if (idate < today) {
alert('Date in the past.');
}
else if (idate > today) {
alert('Date in the future.');
}
Demo
As a side note, when you face hard-to-solve date/time calculations, manipulations, etc, you can use the Moment.js library. It's really useful: Moment.js
the default data parser is reading your idate as 9th febuary 2014, hence today is greater than idate
If you set idate to 09/04/2014 the code runs as expected
var today = new Date();
var idate = new Date('09/04/2014');
console.log(today);
>>>Tue Sep 02 2014 11:48:52 GMT+0100 (BST)
console.log(idate);
>>>Thu Sep 04 2014 00:00:00 GMT+0100 (BST)
You have 2 problems.
The date culture and the time part.
First off, new Date() picks-up the current date, with the current browser's culture plus the time part.
new Date('09/04/2014') does not add a time part, so it starts at 00:00:00 and the culture again depends on the browser. So it may mean 9th of March or 4th of Sept depending on culture.
Remember, that new Date() contains the time part.
If you don't care about the time, create the today date like this:
var now = new Date();
var today = new Date(now.getFullYear(), now.getMonth(), now.getDay());
Another thing is that JS date formatting is 'mm/dd/yyyy'. So change your 'idate' like this:
var idate = new Date('09/02/2014');
You can use < and > to compare the dates. But == will always return false, to check if 2 dates are equal use: if(today.getTime() == idate.getTime())
See the updated fiddle: http://jsfiddle.net/0osh0q8a/3/

Default date format of Javascript/Jquery

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

validate the form using javascript where i have from and to date picker and it should allow only current date and valid time not the next day

I have a form where have to enter from and to date in date picker , but while saving the data the from date and to date should be for the current date. And if i enter to date as tomorrows date it should not allow to save the date.Kindly let me know as how to do this in javascript. May I know what is the correct way to achieve my objective? And even say from time is 10 AM then to time should be 12 pm like not less than from time . Please advice in achieving this using javascript
var today = new Date();
var lastDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
$("#datepicker").datepicker({
startDate: today,
endDate: lastDate,
});
var counter=0;
$("#datepicker").change(function(){
var date1 = $("#datepicker").datepicker('getDate');
date1=date1.getDate();
if(today.getDate() != date1)
{
if(counter%2==0)
alert("please select current date");
}
counter++;
});
Check working fiddle http://jsfiddle.net/GX82L/15/
Done as per your expectation ,like it should prompt if other than current date is selected

Categories