I have got below java script code that will validates date range ... when the user entered the today date or any future dates I have set IsValid to true and then will do the save operation ....
for that purpose I have written below code ..
function Save(e) {
var popupNotification = $("#popupNotification").data("kendoNotification");
var container = e.container;
var model = e.model;
var isValid = true;
var compareDate = e.model.DeliveryDate;
alert(compareDate);
var todayDate = new Date();
var compareDateModified = new Date(compareDate)
alert(compareDateModified);
if (compareDateModified > todayDate || compareDateModified === todayDate) {
isValid = true;
}
else
isValid = false;
e.preventDefault();
if (isValid == false)
{
popupNotification.show("Delivery Date should be today date or Greater", "error");
}
$('#Previous').show();
$('#Next').show();
}
Its working fine when I give the future dates but its not working for today date. I also need to check the today's date. I am not able to figure it out the error alert when I try to enter to the today date .
You are comparing two objects of the same type, but different objects, so that will always result in 'unequal'
If you use date.getTime() you will get better results in your comparison - but only if the time component is the same of course.
Think of the Date object like a timestamp. It is based on the unix-style of timestamps (the amount of seconds since 1st January, 1970) so the Date object isn't the day, it is the Date AND the Time.
What you're comparing is the times as well, which could get a little iffy. If only days matter, try using:
fullCompareDate = compareDateModified.getFullYear() + "/" + compareDateModified.getMonth() + "/" + compareDateModified.getDate();
fullTodayDate= todayDate.getFullYear() + "/" + todayDate.getMonth() + "/" + todayDate.getDate();
if(compareDateModified>todayDate||fullCompareDate==fullTodayDate)
{
//Do something
}
This will compare the date and time to make sure they are greater OR check the current date with the compare date (as strings)
Another solution is to blank out the times on both dates:
compareDateModified.setHours(0,0,0,0);
todayDate.setHours(0,0,0,0);
if(compareDateModified>=todayDate)
{
//Do something
}
You are comparing the compareDateModified to todayDate on the millisecond level. To compare at the day level:
var todayDate = new Date();
todayDate.setHours(0,0,0,0);
//you may also have to truncate the compareDateModified to the first
//second of the day depending on how you setup compareDate
if (compareDateModified >= todayDate) {
isValid = true;
}
Related
I am getting date in string format from API.
End Date 2014-06-03T06:16:52. I need to write an if-else logic and compare the end date and current date.If end date is less than current date then show customer as In Active and if end date is greater than display the Customer as Active.
I have tried following logic but I am not able to understand and get today's time in string fromat.
this.endDate = this.sampleData != null ?
this.sampleData.customerStartDate : null;
this.currentDate = new Date();
var dd = this.currentDate.getDate();
var mm = this.currentDate.getMonth() + 1;
var yyyy = this.currentDate.getFullYear();
this.currentDate = new Date().toLocaleString()
console.log('End Date', this.endDate);
console.log('Current Date: ', this.currentDate);
if (this.endDate == null) {
this.customerStatus = 'Active';
} else {
this.customerStatus = 'In Active';
}
I am getting current date as Current Date: 4/2/2019, 1:23:34 AM
I want to be able to get in same format as End Date.
My main task is to compare the dates how do I achieve it ?
Ideally you want to clean up the date you're getting from an API, and convert it to a JS Date object. You can do this by keeping only the 2014-06-03T06:16:52 part, and giving it to the new Date() constructor.
You can get the current date by calling new Date() without parameters.
You can the turn the dates in to numbers by calling getTime() on each.
You can then compare the numbers.
const incoming_date = new Date('2014-06-03T06:16:52');
const current_date = new Date();
if (incoming_date.getTime() < current_date.getTime() {
// incoming_date is before current_date
} else {
// current_date is before incoming_date
}
as simple as this:
let date=new Date("2014-06-03T06:16:52")
date>new Date()
you could try to express dates in ms since the Unix Epoch with getTime() and compare them
if (currDate.getTime() > endDate.getTime()) {
// set customer to inactive
} else {
// keep customer active
}
I personally like to use moment() for javascript dates. You really just need to have it compare the same format, so you could have something like:
this.currentDate = moment().toISOString();
const dataDate = this.sampleData ? this.sampleData.customerStartDate : null;
this.endDate = moment(dataDate).toISOString();
if (this.endDate > this.currentDate) {
this.customerStatus = 'Active';
} else {
this.customerStatus = 'Inactive';
}
We currently accept HL7 data through mirth and one of the field we process is date of birth, which we receive in PID.7.1 segment of HL7. Currently we just capture it like -
var vDOB = formatDate(msg['PID.7.1'].toString(),"yyyyMMdd");
How can I validate day , month and year component in the date. And also like it should be greater than today's date.
Thanks
You can include a function like this:
var dateChecker = function(dateStr){
if(date.length !=8 && !date.match('[0-9]{8}')) return false;//should be number and length 8
var year = date.substr(0,4);
var month = date.substr(4,2);
var day = date.substr(6,2);
var dateObj = new Date(year,month,day);
if (dateObj == 'Invalid Date') return false;
if(dateObj.getTime() - Date.now() > 0) return false;//compare epoch to check if date is less than current date/time
return true;
}
and then dateChecker(vDOB) should return true/false depending on whether the date is valid or invalid.
Here is my code to find whether the two given dates are equal or not ..
It should allow if today is small or equal. and it should not allow if it is greater date.
var date = '10-11-2015';
var today = '11-11-2016'
alert(today)
alert(date)
if( today <= date )
{
alert("small-or-equal-allow")
}
else
{
alert("larger-not-allow")
}
But its showing not working as expected for few days. What is the mistake and how can i fix it ?
You're comparing strings, not dates. If you want the values to be treated as dates then you need to cast them as dates...
var date = new Date('10-11-2015');
var today = new Date('11-11-2016');
if (today <= date) {
alert("small-or-equal-allow");
}
else {
alert("larger-not-allow");
}
I'm trying to check the users input field to see if it is in the future and if it is in dd/mm/yyyy format but I have no idea why the format part of my code doesn't fire at all! In fact nothing seems to be working on Jsfiddle but at least my "check date in the future" function works locally.
I don't know the correct way of going about this.
to explain this, I've created this FIDDLE
And this is my full javascript code. I need to stay with pure javascript by the way:
function checkdate(){
//var sendDate = document.getElementById('send_year').value + '/' + document.getElementById('send_month').value + '/' + document.getElementById('send_day').value;
var sendDate = document.getElementById('returning_date').value;
sendDate = new Date(Date.parse(sendDate.replace(/-/g,' ')))
today = new Date();
today.setHours(0,0,0,0)
if (sendDate < today) {
//alert('The date can\'t be in the past. Please pick another date.');
document.getElementById('error8').innerHTML = 'The date can\'t be in the past. Please pick another date.';
return false;
}
else
{
document.getElementById('error8').innerHTML = '';
}
if(sendDate.match(/^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/))
{
alert('works out');
}
}
could someone please advise on this issue?
Thanks in advance.
One problem is that you are trying to run sendDate.match, but sendDate has been converted into a Date object so it does not have a match method.
You should run your regular expression before you convert it to a Date, in validation, you typically check that the input conforms to a format before you run further validation like range validation.
Date strings should always be manually parsed, you should never allow the Date constructor or Date.parse to parse strings (the Date constructor parses strings in exactly the same way Date.parse does).
To parse and validate a date string is fairly straight forward, just parse the string and see if you get a valid date:
/* Parse a string in d/m/y format. Separator can be any non–digit
** Avoid conversion of two digit dates to 20th century
** Returns an invalid Date if string is not a valid date (per ECMA-262)
**
** #param {string} s - Date string to parse
** #returns {Date}
*/
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date();
d.setHours(0,0,0,0);
d.setFullYear(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
// Test valid date
document.write(parseDMY('23/01/2016'));
// Test invalid date
document.write('<br>' + parseDMY('35/12/2016'));
Note that this will accept a date like 1/5/16 and treat is as 1 May, 0016. If you want to guarantee that the day and month values have two digits and the year for, then add:
/^\d\d\D\d\d\D\d{4}$/.test(s)
to the validation test at the end. However, I don't like forcing 2 digits for day and month as people don't usually write dates as "01/08/2016", they use "1/8/2016".
First of all, the function needs to be wrapped in <head> (hit the cog in the js tab), otherwise the function can't be found.
But your main problem is that you are using European style of date formatting, so you'll get a "Invalid Date" exception when creating the date. Refer to this question on how to convert it to USA-style and make it available for the Date object (check the reference for all possible uses)
My proposal is:
Date.prototype.fromString = function(str) {
var m = str.match(/([0-9]{2})(-|\/)([0-9]{2})(-|\/)([0-9]{4})/);
if (m == null) {
return null;
}
for (var i = 0; i < m.length; i++) {
if (typeof(m[i]) === 'undefined') {
return null;
};
};
var year = parseInt(m[5]);
var month = parseInt(m[1]) - 1;
var day = parseInt(m[3]);
if (month == 0 || day == 0) {
return null;
}
return new Date(year, month, day);
}
function checkdate(e, obj, errMsgSel){
var sendDate =obj.value;
sendDate = (new Date()).fromString(sendDate);
if (sendDate == null) {
if (e.type == 'blur') {
obj.value = '';
}
return;
}
today = new Date();
today.setHours(0,0,0,0)
if (sendDate < today) {
//alert('The date can\'t be in the past. Please pick another date.');
document.getElementById(errMsgSel).innerHTML = 'The date can\'t be in the past. Please pick another date.';
return false;
}
else
{
document.getElementById(errMsgSel).innerHTML = '';
}
} $(function () {
});
<input onblur="checkdate(event, this, 'error8');" onKeyUp="checkdate(event, this, 'error8');" type='text' name="text1" placeholder='dd/mm/yyyy' id='returning_date'>
<span id='error8' style='color:red;'>format</span> <br><Br>
I have one web application, in this i have to validate one date field of format like mm/dd/yyyy. I searched in the net but i didn't get the proper one. Please help me by providing the new function or by correcting on my code. My code is shown below.. I had called this JS function at onblur event..
function isValidDate() {
var re = new RegExp('^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)dd$');
if (form1.txtDateOfOccurance.value != '' && !form1.txtDateOfOccurance.value.match(re)) {
alert("Invalid date format: " + form1.txtDateOfOccurance.value);
form1.txtDateOfOccurance.value = "";
form1.txtDateOfOccurance.focus();
isEnable();
return false;
}
}
Thanks in advance..
Have a look at http://www.smartwebby.com/DHTML/date_validation.asp, first search result when googling for "javascript date validation"..
Here's the regex you want.
var re = /^(0[1-9]|1[0-2])\/(0[1-9]|[1-3]\d)\/((19|20)\d\d)$/
Though you are probably better off, as inkedmn suggests validating by parsing the input, since MM/dd/yyyy is a recognized date format via Date.parse.
I'd just try parsing the string as a Date object and check the result (assuming you only need to know if it's a valid date or not):
var myDate = Date.parse(form1.txtDateOfOccurance.value);
if(isNaN(myDate)){
// it's not a real date
}
function IsValidDate(str) {
var str2="";
var date = new Date(str);
str2 = (date.getMonth()+1) + "/"
+ date.getDay() + "/"
+ (date.getYear()+1900);
return (str == str2);
}
You can use:
function checkdate(input){
var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
var returnval=false;
if (!validformat.test(input.value))
alert("Invalid Date Format. Please correct and submit again.");
else{ //Detailed check for valid date ranges
var monthfield=input.value.split("/")[0];
var dayfield=input.value.split("/")[1];
var yearfield=input.value.split("/")[2];
var dayobj = new Date(yearfield, monthfield-1, dayfield);
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
alert("Invalid Day, Month, or Year range detected. Please correct and submit again.");
else
returnval=true;
}
if (returnval==false) input.select()
return returnval;
}
This is my implementation. It checks for a valid range and everything.
function validateDate(g) {
var reg = new RegExp("^(([0-9]{2}|[0-9])/){2}[0-9]{4}$");
// Checks if it fits the pattern of ##/##/#### regardless of number
if (!reg.test(g)) return false;
// Splits the date into month, day, and year using / as the delimiter
var spl = g.split("/");
// Check the month range
if (parseInt(spl[0]) < 1 || parseInt(spl[0]) > 12) return false;
// Check the day range
if (parseInt(spl[1]) < 1 || parseInt(spl[1]) > 31) return false;
// Check the year range.. sorry we're only spanning ten centuries!
if (parseInt(spl[2]) < 1800 || parseInt(spl[2]) > 2800) return false;
// Everything checks out if the code reached this point
return true;
}