How to test if a variable is a Moment.js object?

JavascriptMomentjs

Javascript Problem Overview


My application has an HTML form with some inputs populated from the backend and other inputs being entered by the user (in a time input). An onChange function runs through each input when the user changes a value.

The inputs populated from the backend are converted to moment objects, the user-entered dates are mere strings. This means the onChange function encounters some moment objects, and some strings. I need to know which inputs are moment objects and which aren't.

What's the recommended method for testing if a variable is a moment object?

I've noticed moment objects have a _isAMomentObject property but I'm wondering if there's another way to test if a variable is a moment object.

Another option I've tried is calling moment on the variable regardless. This converts the string variables to moment objects and doesn't seem to effect existing moment objects.

Javascript Solutions


Solution 1 - Javascript

Moment has an isMoment method for just such a purpose. It is not particularly easy to find in the docs unless you know what to look for.

It first checks instanceof and then failing that (for instance in certain subclassing or cross-realm situations) it will test for the _isAMomentObject property.

Solution 2 - Javascript

You can check if it is an instanceof moment:

moment() instanceof moment; // true

Solution 3 - Javascript

> moment() instanceof moment;

will always be true, because if you have

  • moment(undefined) instanceof moment
  • moment("hello") instanceof moment

you are always creating a moment object. So the only way is to check like this

  • moment(property).isValid()

Solution 4 - Javascript

Pretty similar to the answer by @Fabien, I'm checking the object if the isValid function is available.

const checkMoment = (date) => {
    if(!date.isValid){ // check if it's not a moment object
        // do something if it's not moment object
        console.log('this is not a moment object');
    }
    else {
        // do something if it's a moment object
        console.log('this is a moment object');
    }
   
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrett DeWoodyView Question on Stackoverflow
Solution 1 - JavascriptJared SmithView Answer on Stackoverflow
Solution 2 - JavascriptNiels HeisterkampView Answer on Stackoverflow
Solution 3 - JavascriptFabien SartoriView Answer on Stackoverflow
Solution 4 - JavascriptAnang SatriaView Answer on Stackoverflow