In Javascript I am trying to write the validation for a date, where the user has to select a future date and not a past date. My code seems to work only when I use a date from last month (e.g. 26/11/2011). This is my script:
<script type="text/javascript" >
function mydate()
{
var d= new Date ();
var day= d.getDate ();
var mon=d.getMonth ();
var year= d.getFullYear ();
var dateformat= day+"/"+mon+"/"+year ;
var get= document.getElementById("txt").value;
if(get >= dateformat )
{
alert ('yes valid');
}
else
{
alert('Date should greater than to date ');
}
}
</script>
You are comparing the date values as strings. This is a textual comparison not a date-wise comparison so it will pretty much never work except by coincidence. You need to parse the date value the user enters into a Date data type and do a comparison that way.
Whenever possible you should avoid writing date manipulation code yourself and try to leverage a known working solution, e.g. the jQuery UI Datepicker.
Related
This question already has answers here:
JavaScript Date Object Comparison
(7 answers)
Closed 2 years ago.
I'm trying to check dates in Javascript for a calendar (fullcalendar), essentially I just want it to not be able to choose past dates:
dateClick: function(info) {
var today = Date.now();
var check = new Date(info.dateStr)
if(check < today)
{
alert('You cannot request dates in the past');
return;
}
else
{
alert('this is the future');
}
},
I'm getting some odd results in that, it seems to calculate the past fine, but also calculates the current day as the past AS well as tomorrow. The day after tomorrow it calculates as the future. No sure what's going on.
info.dateStr gives the format YYYY-mm-dd.
You should coerce to number using +Date or use .getTime() to make sure you are comparing the numeric timestamp values. You're probably fine since you're using Date.now(), which returns a timestamp.
Parsing using the string parsing for Date is strongly discouraged, due to issues like the one in OP:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
Use Date(yyyy, mm, dd, ...) constructor (which uses local time zone) by parsing string manually instead of built-in Date string parsing (which uses UTC if timezone isn't provided).
Using end of the day by adding 24*60*60*1000 to the getTime() value, as that's most likely what you're expecting (same date as today being past is not what most people usually want).
eg: with date to check 05-29-2020, you actually want anything before 05-29-2020 23:59:999
ie: check=05-29-2020 23:59:999 < today=05-29-2020 22:00:000 === false (not past)
or to put it another way the actual intention when:
05-29-2020 => anything from 05-29-2020 00:00 to 05-29-2020 23:59 => actually same as checking 05-30-2020 00:00 - 1 millisecond
dateClick = function(info) {
var today = Date.now()
var check = (([y,m,d])=>new Date(+y,+m-1,+d))(info.dateStr.split(/\D/)).getTime()
+ 24*60*60*1000-1 // add full day so same date as today is not past
console.log(today,check)
if(check < today)
{
alert('You cannot request dates in the past');
return;
}
else
{
alert('this is the future');
}
}
dateClick({dateStr:'2020-05-28'})
dateClick({dateStr:'2020-05-29'})
dateClick({dateStr:'2020-05-30'})
dateClick({dateStr:'2020-05-31'})
you want to compare dates like this: date1.getTime() - date2.getTime()
also, keep in mind, if your goal is to make sure a user is inputing a date that is not in the past, you can use html5 date input with a min set:
<input type="date" min="2020-05-29">
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Extending JavaScript's Date.parse to allow for DD/MM/YYYY (non-US formatted dates)?
Convert dd-mm-yyyy string to date
Entered a date in textbox, for example: 05/09/1985, and I wanted to convert it to 05-Sep-1985 (dd-MMM-yyyy) format. How would I achieve this? Note that the source format may be dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format.
Code Snippet:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val());
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
This code returns 09-May-1985 but I want 05-Sep-1985. Thanks.
You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();
Update
Below you've said:
Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.
That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd, although in practice almost all browsers also support yyyy/mm/dd as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).
Original answer:
If the format is always dd/mm/yyyy, then this is trivial:
var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
split splits a string on the given delimiter. Then we use parseInt to convert the strings into numbers, and we use the new Date constructor to build a Date from those parts: The third part will be the year, the second part the month, and the first part the day. Date uses zero-based month numbers, and so we have to subtract one from the month number.
Date.parse recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy, so the result is wrong.
To fix this, you need either to parse the input yourself (e.g. with String.split) and then manually construct a Date object, or use a more full-featured library such as datejs.
Example for manual parsing:
var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
Example using date.js:
var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");
Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1') change day/month position.
See this http://blog.stevenlevithan.com/archives/date-time-format
you can do anything with date.
file : http://stevenlevithan.com/assets/misc/date.format.js
add this to your html code using script tag and to use you can use it as :
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07
Ok, so I am attempting to test if a date is older than today. I am using jQuery UI's Datepicker to parse the date and assign it to a variable:
//Get Date as String
var $strDate = $(".pmt-date").text();
//Parse Date
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
Then I get today's date and assign it to a variable:
//Get Today's Date
var $strToday $.datepicker.formatDate('mm/dd/yy', new Date());
var $tDate = $.datepicker.parseDate('mm/dd/yy', $strToday);
Now I would like to compare $dtDate with $tDate. This is what I have tried:
if($dtDate > $tDate)
{
alert("Payment Date is Greater");
}
else
{
alert("Today's Date is Greater");
}
When I test this, I ALWAYS get the alert "Today's Date is Greater". I can display my two date variables via an alert, and I see the dates in correct format. So why does this comparison fail to work when the parse is working correctly?
Assuming that the field with class "pmt-date" is the datepicker-controlled <input> element, you need to fetch its value with .val(), not .text().
var $strDate = $(".pmt-date").val();
Your next line of code refers to a variable called "$date", not "$strDate", so:
var $dtDate = $.datepicker.parseDate("mm/dd/yy", $strDate);
Once you've got that, you can just directly compare the Date objects:
if ($dtDate < new Date())
There's no need to turn a newly-constructed Date object into a string and then back into a date. I guess you're Date to string and back in order to strip off the time-of-day part of the date, so that's not really a bad way to do it.
In date comparisons, more than means the date comes after, and less than means the date comes before. Older than would imply that the date comes before, and thus you want to use less than
if($dtDate < $tDate)
I want to compare strings that are dates
if (user_date < date)
date has yyyy-mm-dd format, so it is OK to compare dates as strings, if the user enters a valid user_date in this format.
Unfortunately, user_date is entered by the user, so it could be invalid. In case if it is invalid (or left empty), I want (user_date < date) always to be true.
I have found to set var user_date=''; if user's date is invalid. Is that a good way to make make (user_date < date) for any valid date?
The same question is for (user_date > date) (more than any date).
I've found to set var user_date='A';
I need it for
if (date1 <= date && date2>= date)
//do something
So it works without any additional if then.
P.S. I don't want to enter var user_date='2222-12-31'; because the algorythm will stop working properly in less than 210 years.
I think that is not possible. But what is possible is to get a date for which a comparison is always false — so functionally it behaves the same as NaN does for numbers. So if you invert the test, thus replace (a <= b) with !(a > b), it would work.
$date = new Date(NaN);
if (!($date1 > $date) && !($date2 < $date)) ...
p.s. What's with the dollar signs? Are you confusing Javascript with PHP or Perl? :)
Why not set your min to be 0000-01-01 and your max to be 9999-12-31 ?
I think you can do somethin glike
var date = '2013-03-12';
var $date = new Date(date);
function onChange(el){
var user_date = el.value;
var udate = new Date(user_date);
if(isNaN(udate.getTime()) || udate < $date){
alert('less')
}
}
Demo: Fiddle
Personally I would first validate the date that the user is entering - don't leave it to chance.
I use my own date extensions library here for this kind of stuff:
DP_DateExtensions
The parseFormat() method will let you easily validate your input. Something like this so do well:
Date.parseFormat(InputString, "YYYY-M-D")
The function returns a valid JavaScript date if the entered string matches the format or null if it doesn't. You obviously don't have to send a user message based on this if you have a default behavior you'd like to apply - but the code itself should "know".
In this case - if you want an invalid date to be less than another, known good date, then there are many ways to do it. Most simple is something like this:
InputDate = Date.parseFormat(InputString, "YYYY-M-D");
if ( InputDate || InputDate < GoodDate ) {
Input Date is Invalid or Falls before good date
} else {
Input Date is Falls after good date
};
You don't need to set "false dates" or guess with the right validation and Boolean logic in play and it will work until the world stops spinning (in theory).
You can you use the compare() method in the library to do any kind of greater/less than comparison to any precision.
Hope this helps.
I have two jQuery datepickers that once changed, will trigger some ajax to grab all information between the two dates.
I want to run some code to check that the first date is smaller than the second, by converting to a date using this code:
function FormatUkDate(dateStr) {
dateStr = dateStr.split("/");
return new Date(dateStr[2], dateStr[1] - 1, dateStr[0]);
}
This works great, but the problem is even if I enter a date of '50/08/2011' it still validates and converts that to a Javascript date, I believe by adding the additional number of days to the start date.
Is there a way to properly validate this please?
Thanks!
you can validate using a jquery masked plugin,you can check it http://digitalbush.com/projects/masked-input-plugin/
For working with dates you can try to use datejs library. It has many features including validating dates. To solve your problem you can use Date.validateDay method. Also you can use datejs to compare dates.
hm... I guess a plugin would be a better solution, but for what it's worth:
function FormatUkDate(dateStr) {
dateStr = dateStr.split("/");
var newDate = new Date(dateStr[2], dateStr[1] - 1, dateStr[0]);
return newDate.getDate() == Number(dateStr[0]) && newDate.getMonth() == Number(dateStr[1]) - 1? newDate : null;
}
returns null if the date carries over to the next month.
Edit
New code :P