Validate date in Javascript - javascript

Note that this seems like a question that is asked many times, but somehow I can't get the most common solution to work.
Most answers revolve around a solution like this one:
function isValidDate(){
var dateString = '2001/24/33';
return !isNaN(Date.parse(dateString));
}
In Firefox this returns a false as the result of that Date.parse is a number; 1041462000000.
How do I fix this..?

A good way to do this is to create new date object based on the string and compare the result of that object with the input string. If it is not the same, the date was invalid and JS did a fallback to a closer (valid) date. Something like this:
function isValidDate(str){
var split = str.split('/');
var date = new Date(split[0], split[1]-1, split[2]);
return (date.getFullYear() == split[0] && date.getMonth()+1 == split[1] && date.getDate() == split[2]);
}
call with:
var isValid = isValidDate('2001/24/33');
Note: in this case the input string is assumed to be in a specific format. If your sure that it's always the same format there is not problem. If not, your need the work some more on this code.
As a sidenote: Use moment.js if you need to do extensive date operations.

I suggest to use http://www.datejs.com/.
Very cool library.

Related

Transforming date string from one timezone to another in JavaScript

I have spent several hours trying to figure out how JavaScript works with dates. I have come across this question, but it does not seem to asnwer my specific question.
My input is a string like this:
"2018-02-19T07:00:00Z"
My goal is to transform this into a datetime which would differ from the original date by 4 hours - WITHOUT ANY TIMEZONE (!):
"2018-02-19T11:00:00Z"
Is it possible in JavaScript ?
Check out all the functions relating to "UTC" and "ISO" on the Date docs.
var input = "2018-02-19T07:00:00Z";
var t = new Date(input);
t.setUTCHours(t.getUTCHours()+4)
var iso = t.toISOString().replace(/\.\d+/,'');
console.log(iso);
(I added a little regex to get rid of the milliseconds so it matches your expected output, you can remove that if the miliseconds don't matter, it's valid ISO either way.)
It's 4 lines of code, you do not need a library.
In addition to #Occam'sRazor answer, you could also do it without using the Date object, by using some String manipulations :
var str = "2018-02-19T07:00:00Z";
var timeZoneHours = +str.split('-').pop().split(':')[0].split('T').pop() + 4;
console.log(timeZoneHours);
str = str.substring(0,str.indexOf(':') -2) + (timeZoneHours < 10 ? '0' + timeZoneHours.toString() : timeZoneHours.toString()) + str.substring(str.indexOf(':'), str.length);
console.log(str);

Javascript Date object returns 'invalid date' for my date string

I want to create a Date object in Javascript using this string 04/21/2014 12:00p
When passed to the constructor (new Date('04/21/2014 12:00p')), it returns Invalid Date.
I've seen other posts which manipulate the string in order to fulfill the requirements of a valid dateString, however that is not what I want. I want Javascript to recognize my date format (m/dd/yy h:mmt). In Java, something like that is simple, I imagine that there would be a similar way in Javascript.
How can I get the Date object to recognize my format?
This is trivial only when using a library like moment.js:
var dt = moment("04/21/2014 12:00p","MM/DD/YYYY h:mma").toDate();
Otherwise, you would have considerable string manipulation to do. Also you would have to account for users in parts of the world that use m/d/y or other formatting instead of the y/m/d formatting of your input string.
If this string is being sent from some back-end process, you might consider changing the format to a standard interchange format like ISO-8601 instead. Ex. "2014-04-21T12:00:00"
To manipulate the string in order to fulfill the requirements, could be a way, but you need to take care of all browser issues.
A more quick and dirty way is use moment.js library. It helps on formatting matters too.
if (String.prototype.dateFromJava == null)
{
String.prototype.fromJava = function (sDateString)
{
var aDateOrTime = sDateString.splt(" ");
var aDateParts = aDateOrTime[0].split("/");
var aTimeParts = aDateOrTime[1].split(":");
var oDate = null;
/* just get the pieces and passing them in to new Date(), return oDate */
}
}

Javascript: the minimum date that is always less than any other date

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.

how to check if one date comes before anotherone in javascript

I have 2 dates and I one to check if one date comes before another one.
I know you have to parse the date to a JS date object and then check it with milliseconds.
But the problem is, in my database dateTimes are stored like this.
10-mei-2012 09:36
So my question is how can I compare two of these dates and check that date 1 comes before date2? Oh and for the record, I am also using jquery to get these values.
var dateB = $('#DATUM_BEGIN').val();
var dateE = $('#DATUM_EINDE').val();
kind regards
Stef
In that format you can compare strings as-is, it is safe. So use just
if (dateB < dateE) ...
http://www.datejs.com/ could be helpful. it is a jquery Plugin to compare Dates.
The format you show is "mostly" ISO-8601 combined-date format which is by design comparable as plain text.
The only difference between what you have and pure ISO-8601 is that there would need to be a 'T' where the space character is.
http://en.wikipedia.org/wiki/ISO_8601
So, if you can sort the strings you know which one comes first.
Here's a function found while googling that converts MySQL DATETIME to a JS Object
function mysqlTimeStampToDate(timestamp) {
var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}
Here's one example of how to use it:
$(function(){
var dateB = mysqlTimeStampToDate($('#DATUM_BEGIN').val());
var dateE = mysqlTimeStampToDate($('#DATUM_EINDE').val());
if(dateB < dateE){
// dateB is older
} else {
// dateB is newer
}
});

Is this a good way to check for a valid date in JavaScript?

Please correct or explain how my over-simplification is incorrect as I am not a JavaScript expert.
But I just need to know if an object is a valid date. This will only come from user input (ie, text box).
var is_valid_date = function(date) {
try {
var d = new Date(date);
return true;
}
catch(e) {
return false;
}
}
YOU have to decide what form of dates you want to accept.
Then, once you know what forms you want to accept, you can then check the spec for new Date(str) or date.parse() on MDN and see if it supports exactly what you want and if it does the right things on error conditions (it probably will not). If not, then you will have to do some manual parsing.
If you want further help from us, you will need to specify what forms of date you want to accept.
There are also some browser differences as javascript has moved to support additional date formats and earlier browsers had some inconstencies between them which all means you'll want to build yourself a simple test script with a bunch of legal and illegal date format strings and see if your validity detection does what you want in several browsers. This isn't rocket science to get it right, but it's not trivial either and requires some work unless you only want to accept what the original date object supported (which is unlikely).
If this were my code, I'd probably decide that it's far less work to do manual parsing of your desired input format that you know with 100% certainty will work in all browsers because it's your own manual parsing. I'd probably use a regex to parse the date and then convert each component to a number and check each component for validity. You can then feed those numeric components to the Date constructor to create the Date object.
If you can tell by now, the built-in date class isn't very useful for user entered input. If you're willing to use a library for this, the date.js library has a ton of useful functionality in this regard.
Here's an example of a manual parsing function that accepts these US formats:
mm-dd-yyyy
mm dd yyyy
mm/dd/yyyy
JS Code:
function checkDate(str) {
var matches = str.match(/(\d{1,2})[- \/](\d{1,2})[- \/](\d{4})/);
if (!matches) return;
// parse each piece and see if it makes a valid date object
var month = parseInt(matches[1], 10);
var day = parseInt(matches[2], 10);
var year = parseInt(matches[3], 10);
var date = new Date(year, month - 1, day);
if (!date || !date.getTime()) return;
// make sure we have no funny rollovers that the date object sometimes accepts
// month > 12, day > what's allowed for the month
if (date.getMonth() + 1 != month ||
date.getFullYear() != year ||
date.getDate() != day) {
return;
}
return(date);
}
And a demo with some test cases: http://jsfiddle.net/jfriend00/xZmBY/
If you want the Euro format, it's a trivial matter to switch the code to that. In either case, you have to decide which format you accept, code for it and then communicate to the user which format is required. If you think this is messy, then perhaps you will see why so many sites use a date calendar picker that doesn't have this complexity.
Please correct or explain how my over-simplification is incorrect as I am not a JavaScript expert.
But I just need to know if an object is a valid date. This will only come from user input (ie, text box).
Here's why it's an oversimplification.
First of all, it sounds like you really want to check the validity of a string representation of a Date object. This is not particularly useful by itself, because you are going to want to use the date for something in your script, send it to the server, etc.
If you want to use the date in your script, there are caveats.
new Date('2020-10-10') // Fri Oct 09 2020 20:00:00 GMT-0400 (EDT)
If you want to pass it to the server, you'll need to do more than just check validity– you'll need to use a format that your server side code can interpret.
If that's the case, you could consider normalizing the string into a format of your choice. You'd want to be able to create equivalent dates from the normalized strings in both your client and server side code. For simplicity, the format can be human-readable (not a timestamp), and you can replace the value of the text input with the normalized string.
Checking the validity of the string can simply be a part of normalization... have the function return false or an empty string if the input was bad, don't change the text input's value, and instead show a message indicating that the value is invalid:
// assume `birthday` is a text input.
birthday.onblur = function() {
var dateString = normalizeDate(birthday.value);
if (dateString) {
validator.style.display = 'none';
birthday.value = dateString;
} else {
validator.style.display = 'block';
}
};
Here's an example of what the normalizeDate function might look like. This example uses the format 'yyyy-mm-dd', you can change it to suit your needs.
function normalizeDate(dateString) {
// If it's not at least 6 characters long (8/8/88), give up.
if (dateString.length && dateString.length < 6) {
return '';
}
var date = new Date(dateString),
month, day;
// If input format was in UTC time, adjust it to local.
if (date.getHours() || date.getMinutes()) {
date.setMinutes(date.getTimezoneOffset());
}
month = date.getMonth() + 1;
day = date.getDate();
// Return empty string for invalid dates
if (!day) {
return '';
}
// Return the normalized string.
return date.getFullYear() + '-' +
(month > 9 ? '' : '0') + month + '-' +
(day > 9 ? '' : '0') + day;
}
Here's the obligatory live demo.
new Date() doesn't throw an exception if month>12 for example, you can use Date.parse() and test the returned value with isNaN()

Categories

Resources