Validating a date range client side - javascript

I have 2 TextBoxes that expect a date in the format mm/dd/yyyy
Ex:
03/20/2013
Before I even bother to make the ajax call, I want to try and turn these into JS Dates. How could I check if:
Both Dates are in the mm/dd/yyyy format and if they are, then From must be less than to.
Thanks

I'd recommend using moment for this one. Moment is a js library especially for dates, and evaluating dates. Your two text boxes start off as strings, so you need to init 2 moment()'s with each. Then verify they're both moment objects. If so, it's then a simple matter to make sure the one is after the other.
Here's the link to moment: http://momentjs.com/
Here's code I may use:
var tb1 = $("#tb1").text(); // get string from "date box 1"
var tb2 = $("#tb2").text(); // get string from "date box 2"
//get timestamp val's so they can be used in moment initialization
var date1 = tb1.split("/");
var date2 = tb2.split("/");
//create moments
var mom1 = moment([date1[2], date1[1], date1[0]);
var mom2 = moment([date2[2], date2[1], date2[0]);
function validate(mom1, mom2){
//validate both dates are actual dates
if (mom1.isValid() && mom2.isValid()){
//compare timestamps to ensure 2nd timestamp is larger
if(mom1.unix() < mom2.unix()){
return true;
} else {
return false;
}
} else {
//strings aren't dates, return error
$.error("not valid dates");
}
}

Related

react AG-grid: date filter in range - doesn't work if you reverse the dates

I'm trying to set up a date filter on ag-grid as per this link.
The main difference is that ag-grid prefers date format dd/mm/yyyy whereas my dates are in yyyy-mm-dd.
comparator:function (filterLocalDateAtMidnight, cellValue){
let dateParts = cellValue.split("-");
let cellDate = new Date(Number(dateParts[0]), Number(dateParts[1]) - 1, Number(dateParts[2]));
if (cellDate < filterLocalDateAtMidnight) {
return -1;
} else if (cellDate > filterLocalDateAtMidnight) {
return 1;
} else {
return 0;
}
The above code works conventionally, although I noticed a special case.
when selecting the date filter condition "inRange", and setting the dates e.g:
dateFrom = 2017-07-13
dateTo = 2017-08-20
it works fine and i see records between those two dates, but if you reverse the dates, i.e.:
dateFrom = 2017-08-20
dateTo = 2017-07-13
No records show. How can I overcome this glitch? Conventionally, the user would put the earliest date first, but that doesn't mean the above scenario isn't possible

how to compare two dates 29-July-2016 and 01-Aug-2016 in angularjs

var startDateValuecmp = 29-July-2016; I have start Date Value in 29-July-2016.
var endDateValuecmp=01-Aug-2016; end Date Value 01-Aug-2016.
I want to compare this formate of date.
if (startDateValuecmp < endDateValuecmp) {
if (confirm("Please Check Event Date And Follow Up Date!!! Do you want to continue ?") == true) {
return true;
} else {
return false;
}
}
Angular can direclty compare data if the input is well formatted.
If they're date object just compare them directly without .getTime() using ng-if
You can pass date to Date builtin JavaScript class and then compare it
var startDateValuecmp = new Date('29-July-2016');
var endDateValuecmp = new Date('01-Aug-2016')
if ( startDateValuecmp < endDateValuecmp )
{
...
This will return boolean true or false based on condition.
This will return date in localtime zone, if concern about it use Date.UTC()
Refer this MDN Document.
Update:
This can't be invalid. Press button to Run this code
var startDateValuecmp = new Date('29-July-2016');
console.log("startDateValuecmp:", startDateValuecmp);

Date Validation : validating Return date is after departure date using datepicker( )

I am trying to validate that the return date is after departure, I cant think of how to write the function. I was thinking one approach would be to strip the ( / ) forward slashes from the dates picked from the datepicker ( ) so they are whole integers and store them into new variables then use a if/else statement to alert if the return date < departure date.
Anyone know if this would be the right way to go?? if so how do i go taking the input from the datepicker() and strip the slashes??
$(document).ready(function(){
var destinations = [];
destinations[0]='italy';
destinations[1]='france';
destinations[2]='california';
destinations[3]='miami';
destinations[4]='Denver';
destinations[5]='chicago';
var departing = $('#departing').datepicker();
var returning = $('#returning').datepicker();
$('#destination').autocomplete({source:destinations});
$('input').focus(function(){
$(this).css('outline-color', 'skyblue');
}); // end focus function
}); // end document Ready
You don't need to parse the date yourself. Just call $(selector).datepicker('getDate') and you will get a date object.
If you have both dates you can simply compare them to each other.
function validate() {
var departing = $('#departing').datepicker('getDate');
var returning = $('#returning').datepicker('getDate');
//do wathever you want if returning is before departing
alert(departing > returning);
}
You can also restrict the pickable dates like this:
$('#departing').on('change', function() {
$('#returning').datepicker("option", "minDate", $('#departing').datepicker('getDate'));
});
$('#returning').on('change', function() {
$('#departing').datepicker("option", "maxDate", $('#returning').datepicker('getDate'));
});
You could simply achieve this using Date Picker functionality. Below lines of code will give you the Date object of the respective Date Picker ...
var departing= $("#departing").datepicker("getDate");
var returning= $("#returning").datepicker("getDate");
And for comparison you could simply use
if (departing < returning) {
to find out return date is after departure .
Or you can look into the Date Picker Date parser method for getting Date Object directly ,
var departing= $.datepicker.parseDate("date-picker-format",$("#returning").val());
var returning= $.datepicker.parseDate("date-picker-format",$("#returning").val());
//e.g date-picker-format = dd-mm-yy

how to compare the date in xml row with today's date

I have one xml file which is retrieved using jquery in sharepoint. One of the row of the xml is like below.
<z:row ows_Title='Have dinner party with Host' ows_Due_x0020_Date='2012-05-10 00:00:00' ows_MetaInfo='1;#' ows__ModerationStatus='0' ows__Level='1' ows_ID='1' ows_UniqueId='1;#{2A8F277A-C95B-420C-89A9-3B979F95C8F4}' ows_owshiddenversion='3' ows_FSObjType='1;#0' ows_Created='2012-10-25 03:19:35' ows_PermMask='0x7fffffffffffffff' ows_Modified='2012-10-29 00:56:09' ows_FileRef='1;#personal/Inclusions/Lists/Events/1_.000' />
Now i want to retireve the "Due Date" column and compare with the today's date. For retrieving date there is no issue. But how to compare the both dates? For comparing the date with today I used like this.
var k = new Date();
var year = k.getYear();
var month = k.getMonth();
var day = k.getDate();
var fulldate = year+"-"+month+"-"+day
But it is displaying only with date. In xml we are getting time also. I dont want to compare with time. I want to compare with only dates. How to achieve it? I want to put that whole process in the following function.
$(xData.responseXML).find("z\\:row").each(function() {
//here i want to compare that date column with present date
});
Finally i want, the date coming in the xml is less than the today's date or not?
Something like this:
function isPastDate( date ) {
return (new Date( date )).getTime() < (new Date()).getTime();
}
Highly recommend Date.js library for all the comparison and formatting methods that can make a lot of date work greatly simplified
http://www.datejs.com/
finally the required comparison like below.
function compareDates(passdate)
{
var splitdate = passdate.split(" ");
var splitdate1 = splitdate[0].split("-");
var newdate = splitdate1[1]+"-"+ splitdate1[2]+"-"+splitdate1[0];
return ((Date.parse(newdate)) < (new Date()).getTime());
}

How to check if input date is equal to today's date?

I have a form input with an id of 'date_trans'. The format for that date input (which is validated server side) can be any of:
dd/mm/yyyy
dd-mm-yyyy
yyyy-mm-dd
yyyy/mm/dd
However, before posting the form, I'd like to check if the date_trans field has a date that is equal to today's date. Its ok if the date taken is the client's date (i.e. it uses js), since I run a double check on the server as well.
I'm totally lost on how to do the date comparrison in jQuery or just plain old javascript. If it helps, I am using the jquery datepicker
A simple date comparison in pure JS should be sufficient:
// Create date from input value
var inputDate = new Date("11/21/2011");
// Get today's date
var todaysDate = new Date();
// call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
// Date equals today's date
}
Here's a working JSFiddle.
for completeness, taken from this solution:
You could use toDateString:
var today = new Date();
var isToday = (today.toDateString() == otherDate.toDateString());
no library dependencies, and looking cleaner than the 'setHours()' approach shown in a previous answer, imho
Try using moment.js
moment('dd/mm/yyyy').isSame(Date.now(), 'day');
You can replace 'day' string with 'year, month, minute' if you want.
function sameDay( d1, d2 ){
return d1.getUTCFullYear() == d2.getUTCFullYear() &&
d1.getUTCMonth() == d2.getUTCMonth() &&
d1.getUTCDate() == d2.getUTCDate();
}
if (sameDay( new Date(userString), new Date)){
// ...
}
Using the UTC* methods ensures that two equivalent days in different timezones matching the same global day are the same. (Not necessary if you're parsing both dates directly, but a good thing to think about.)
Just use the following code in your javaScript:
if(new Date(hireDate).getTime() > new Date().getTime())
{
//Date greater than today's date
}
Change the condition according to your requirement.Here is one link for comparision compare in java script
The following solution compares the timestamp integer divided by the values of hours, minutes, seconds, millis.
var reducedToDay = function(date){return ~~(date.getTime()/(1000*60*60*24));};
return reducedToDay(date1) == reducedToDay(date2)
The tilde truncs the division result (see this article about integer division)
Date.js is a handy library for manipulating and formatting dates. It can help in this situation.
Try this
// method to check date is less than today date
isLessDate(schedule_date : any){
var _schedule_date = new Date(schedule_date);
var date = new Date();
var transformDate = this.datePipe.transform(date, 'yyyy-MM-dd');
var _today_date = new Date(''+transformDate);
if(_schedule_date < _today_date){
return 'small'
}
else if(_schedule_date > _today_date){
return 'big'
}
else {
return 'same'
}
}
The Best way and recommended way of comparing date in typescript is:
var today = new Date().getTime();
var reqDateVar = new Date(somedate).getTime();
if(today === reqDateVar){
// NOW
} else {
// Some other time
}
TodayDate = new Date();
if (TodayDate > AnotherDate) {} else{}
< = also works, Although with =, it might have to match the milliseconds.
There is a simpler solution
if (inputDate.getDate() === todayDate.getDate()) {
// do stuff
}
like that you don't loose the time attached to inputDate if any

Categories