How to check if obj is of type luxon?
I am writing a date adapter for Angular Material, and need a function that returns a boolean if the provided object is a luxon DateTime.
Something like this (from moment):
isDateInstance(obj: any): boolean {
return moment.isMoment(obj);
}
What I have is this so far - is this good enough?:
isDateInstance(obj: any): boolean {
try {
const luxonObject = DateTime.fromObject(obj);
return luxonObject.isValid;
} catch (error) {
return false;
}
}
Solution 1:
I think that your code is fine, I would suggest that you can use native instanceof
.
const DateTime = luxon.DateTime;
function isDateInstance(obj) {
return obj instanceof DateTime;
}
console.log( isDateInstance('') );
console.log( isDateInstance({}) );
console.log( isDateInstance(new Date()) );
console.log( isDateInstance(DateTime.local()) );
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>
EDIT:
Luxon has added isDateTime
method in v.1.6.0
that
Check if an object is a DateTime. Works across context boundaries
so an updated solution can be the following:
const DateTime = luxon.DateTime;
function isDateInstance(obj) {
return DateTime.isDateTime(obj);
}
console.log( isDateInstance('') );
console.log( isDateInstance({}) );
console.log( isDateInstance(new Date()) );
console.log( isDateInstance(DateTime.local()) );
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.js"></script>
From v.1.6.0
until v.1.8.3
isDateTime
will give undefined
instead of false
due to an issue.