Check if the given string is a date object - javascript

I need to check whether the given string is date object or not.
Initially I used
Date.parse(val)
If you check Date.parse("07/28/2014 11:23:29 AM"), it'll work.
But if you check Date.parse("hi there 1"), it'll work too, which shouldn't.
So I changed my logic to
val instanceof Date
But for my above date string, "07/28/2014 11:23:29 AM" instanceof Date it returns false.
So, is there any way with which I can appropriately validate my string against Date?

You can use Date.parse to check if it is a date or not using below code. Date.parse() return number if valid date otherwise 'NaN' -
var date = Date.parse(val);
if(isNaN(date))
alert('This is not date');
else
alert('This is date object');
For more information - Date Parse()

function isDate(val) {
var d = new Date(val);
return !isNaN(d.valueOf());
}
Hope helps you

Related

How to check if 2017-03-29T06:45:00.000Z is equal to the date and time now?

I have a date with the format 2017-03-29T06:45:00.000Z, how do I check if it is equal or less to the date and time now?
If I check with
var currentTime = new Date();
if("2017-03-29T06:45:00.000Z" <= currentTime){
its not right since current date is in the format Wed Mar 29 2017 08:59:18 GMT+0200(CEST)
Any input appreciated, thanks
You are trying to compare a string to a Date Object. Because the two data types do not match, javascript tries to compare them by their value and calls currentTime.valueOf(). This evaluates to a integer like 1490781568805. Javascript then tries to compare the string to the evaluated integer. The result is different than you might expect, because the individual char codes of the string are compared to the integer.
"2017-03-29T06:45:00.000Z" <= new Date() // string compared to the Date object
"2017-03-29T06:45:00.000Z" <= new Date().valueOf() // javascript trying get a value for the date object
"2017-03-29T06:45:00.000Z" <= 1490781568805 // evaluates to false
You can just parse your date string to a Date object using Date.parse()
Date.parse("2017-03-29T06:45:00.000Z") <= new Date() // two Date objects are compared

Determine if string is Date or Number

I'm trying to determine if a string is a number or a date.
Here is my code:
this._getFieldFormat = (value) => {
// check if is date
let d = new Date(value);
if (!isNaN( d.getTime() ) ) {
return 'date';
}
// check if is boolean
// isNaN(false) = false, false is a number (0), true is a number (1)
if(typeof value === 'boolean'){
return 'boolean';
}
// check if a string is a number
if(!isNaN(value)){
return 'number';
}
return typeof value;
};
It works for a date like: 2016-04-19T23:09:10.208092Z.
The problem is that 1 look to be a valid date (Wed Dec 31 1969 16:00:00 GMT-0800 (PST)) and isNaN(new Date()) is return false (a date is a number).
Any idea on how to get out of this loop?
So what is happening is called coercion. Since javascript is dynamic typing when you give it two different types the js engine tries to coerce one of the types into something reasonable or what it thought you meant.
For instance:
isNan("37"); is false because "37" is converted to the number 37
isNaN(new Date()) is return false (a date is a number)
It converted Date to a number so this is correct.
However, invalid values in date strings not recognized as ISO format as defined by ECMA-262 may or may not result in NaN, depending on the browser and values provided
So
new Date('23/25/2014'); // NON-ISO string with invalid date values
So this will return NaN in all browsers that comply with ES5 and later.
Also to do a stricter check you can use:
Number.isNan(new Date()); // This should return true
So to recap make sure the date conform to the ISO standard or it will be NaN and use the stricter check. Hope this helps.
In general and from a Javascript design point of view, however, I don't think you can do it by design. Any number between 8640000000000000 and the earliest date in terms of a number -8640000000000000 can be converted to date (represented as time in milliseconds from 01 January, 1970 UTC).
Therefore, any number not falling is this range cannot be a date. And any number falling in range would be a valid date or a number and you gotta use context to determine if you want to interpret it as a number or a date.
You could however do a naive implementation to test if number is a valid date or not, but that's the best you can do, without context.
Determining whether a date is a number or not can be a bit easier. Because a human-readable representation of date will return true by isNaN() thereby determining that it's definitely not a number. Then you would go on and check if that string is a date or not, which you already did in your function.

How to throw an error whenever an invalid date object is created? [duplicate]

This question already has answers here:
Detecting an "invalid date" Date instance in JavaScript
(52 answers)
Closed 6 years ago.
I raised strange issue:
var d = new Date("2016--01---01");
Would create object without any errors. Actually, first question is - why?
But then i need to get string from this object - i am trying to
d.toString(); // 'Invalid Date'
d.getTime(); // NaN
d.toJSON(); // null
What it is possible ways to get string or check that it is incorrect?
You can simply check it's a valid number when converted to one:
var ok = !isNaN(d);
(this conversion is the same than taking d.getTime()).
But be warned that a valid date might be not the desired date. You usually use a verified date format. Libraries like moment.js might help you on that.
Create a factory type function which throws an error if the string given produces an invalid date, but returns the date if it's valid
var d = createDate("2016--01---01")
createDate = function(str) {
var date = new Date(str)
if(date instanceof Date && !isNaN(date.valueOf())) return date
else throw Error('invalid date')
}

Momentjs : How to prevent "Invalid date"?

I have the following code :
var fomattedDate = moment(myDate).format("L");
Sometimes moment(myDate).format("L") returns "Invalid date", I want to know if there is a way to prevent that and return an empty string instead.
TL;DR
If your goal is to find out whether you have a valid date, use Moment's isValid:
var end_date_moment, end_date;
jsonNC.end_date = jsonNC.end_date.replace(" ", "T");
end_date_moment = moment(jsonNC.end_date);
end_date = end_date_moment.isValid() ? end_date_moment.format("L") : "";
...which will use "" for the end_date string if the date is invalid.
Details
There are two very different things going on here.
First:
0000-00-00T00:00:00 is an invalid date. There's no month prior to January (which is month #1 in that format), nor a day of a month prior to day #1. So 0000-00-00 makes no sense.
0000-01-01T00:00:00 would be valid — and moment("0000-01-01T00:00:00").format("L") happily returns "01/01/0000" for it.
If you use a valid date (such as your 2015-01-01T00:00:00 example), the code is fine.
Second:
console.log(Object.prototype.toString.call(end_date));
It returns [object String] even with a valid date, so the if condition doesn't working in my case.
Of course it does: format returns a string, and you're using format to get end_date.
If you want to know if a MomentJS object has an invalid date, you can check like this:
if (theMomentObject.isValid()) {
// It has as valid date
} else {
// It doesn't
}
If you want to know if a Date object has an invalid date:
if (!isNaN(theDateObject)) {
// It has as valid date
} else {
// It doesn't
}
...because isNaN will coerce the date to its primitive form, which is the underlying number of milliseconds since Jan 1 1970 00:00:00 GMT, and when a date has an "invalid" date, the number it contains is NaN. So isNaN(theDateObject) is true when the date is invalid.

Can't Compare dates using jQuery UI's datepicker

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)

Categories

Resources