How to check whether an object is a date?
As an alternative to duck typing via
typeof date.getMonth === 'function'
you can use the instanceof
operator, i.e. But it will return true for invalid dates too, e.g. new Date('random_string')
is also instance of Date
date instanceof Date
This will fail if objects are passed across frame boundaries.
A work-around for this is to check the object's class via
Object.prototype.toString.call(date) === '[object Date]'
type of Date object
Lemme tell you a basic thing. The articles in W3Schools are definitely outdated so you must not rely on it. Yes, when you give this in console:
typeof (new Date())
The above code returns object
because the JavaScript has only a few primitive types:
You can check if it is a date
object or not using:
(new Date()) instanceof Date
The above code will return true
. This is the right way of checking if the particular variable is an instance of a particular type.
Is there a way to check if a variable is a Date in JavaScript?
Use instanceof
(myvar instanceof Date) // returns true or false
Detecting an invalid date Date instance in JavaScript
Here's how I would do it:
if (Object.prototype.toString.call(d) === "[object Date]") {
// it is a date
if (isNaN(d)) { // d.getTime() or d.valueOf() will also work
// date object is not valid
} else {
// date object is valid
}
} else {
// not a date object
}
Update [2018-05-31]: If you are not concerned with Date objects from other JS contexts (external windows, frames, or iframes), this simpler form may be preferred:
function isValidDate(d) {
return d instanceof Date && !isNaN(d);
}
Update [2021-02-01]: Please note that there is a fundamental difference between "invalid dates" (2013-13-32
) and "invalid date objects" (new Date('foo')
). This answer does not deal with validating date input, only if a Date instance is valid.
Determine if datetime object is date or datetime
If you look at the source code for the datetime
class (or simply command+click on datetime
using an IDE on Mac), you'll notice that the datetime
class actually is a subclass of date
:
class datetime(date):
...
Therefore, isinstance(dtDate, date)
will be true even if dtDate
is a datetime
object.
You can fix this by checking for the more specific type first:
if isinstance(dtDate, datetime):
sDate = dtDate.strftime('%x %X')
elif isinstance(dtDate, date):
sDate = dtDate.strftime('%x')
Full code:
from datetime import date, datetime
# dtDate = date.today()
dtDate = datetime.now()
if isinstance(dtDate, datetime):
sDate = dtDate.strftime('%x %X')
elif isinstance(dtDate, date):
sDate = dtDate.strftime('%x')
print(sDate)
Python: how can I check whether an object is of type datetime.date?
i believe the reason it is not working in your example is that you have imported datetime
like so :
from datetime import datetime
this leads to the error you see
In [30]: isinstance(x, datetime.date)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/<ipython-input-30-9a298ea6fce5> in <module>()
----> 1 isinstance(x, datetime.date)
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
if you simply import like so :
import datetime
the code will run as shown in all of the other answers
In [31]: import datetime
In [32]: isinstance(x, datetime.date)
Out[32]: True
In [33]:
Check if a string is a date value
Would Date.parse()
suffice?
See its relative MDN Documentation page.
Date.parse
returns a timestamp if string date is valid. Here are some use cases:
// /!\ from now (2021) date interpretation changes a lot depending on the browser
Date.parse('01 Jan 1901 00:00:00 GMT') // -2177452800000
Date.parse('01/01/2012') // 1325372400000
Date.parse('153') // NaN (firefox) -57338928561000 (chrome)
Date.parse('string') // NaN
Date.parse(1) // NaN (firefox) 978303600000 (chrome)
Date.parse(1000) // -30610224000000 from 1000 it seems to be treated as year
Date.parse(1000, 12, 12) // -30610224000000 but days and month are not taken in account like in new Date(year, month,day...)
Date.parse(new Date(1970, 1, 0)) // 2588400000
// update with edge cases from comments
Date.parse('4.3') // NaN (firefox) 986248800000 (chrome)
Date.parse('2013-02-31') // NaN (firefox) 1362268800000 (chrome)
Date.parse("My Name 8") // NaN (firefox) 996616800000 (chrome)
How to check if a Date object or Calendar object is a valid date (real date)?
Using Java Time API, this can be done using the STRICT
ResolverStyle
:
Style to resolve dates and times strictly.
Using strict resolution will ensure that all parsed values are within the outer range of valid values for the field. Individual fields may be further processed for strictness.
For example, resolving year-month and day-of-month in the ISO calendar system using strict mode will ensure that the day-of-month is valid for the year-month, rejecting invalid values.
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy")
.withResolverStyle(ResolverStyle.STRICT);
LocalDate.parse("02-31-2016", formatter);
}
This code will throw a DateTimeParseException
since it is not a valid date.
By default, a formatter has the SMART
ResolverStyle
:
By default, a formatter has the SMART resolver style.
but you can change this by calling withResolverStyle(resolverStyle)
on the formatter instance.
Related Topics
How to Merge Two JavaScript Objects Together in Es6+
How to Upload a File Using Jquery.Ajax and Formdata
Using Async/Await Inside a React Functional Component
(Deep) Copying an Array Using Jquery
JavaScript - How to Get the Url of Script Being Called
Add Event Handler to HTML Element Using JavaScript
How to Declare a Global Variable in a .Js File
How to Call Fromlatlngtodivpixel in Google Maps API V3
Why Is Proxy to a Map Object in Es2015 Not Working
Clearrect Function Doesn't Clear the Canvas
Triggering a JavaScript Click() Event at Specific Coordinates
Retrieving Binary File Content Using JavaScript, Base64 Encode It and Reverse-Decode It Using Python
Getting the User Id from a Database Trigger in Cloud Functions for Firebase
How to Redefine a JavaScript Class's Method