momentjs internal object what is "_d" vs "_i"

Pay no attention to those. Use the various output functions, such as .format() instead. See the Moment.js guidance on this topic. In short, all fields that are prefixed with an underscore (_) should be considered off limits.

The moment internals have some quirks due to how the Date object works. All of the functions in the public API take them into account, but you probably don't want to figure them out yourself.

Just to be complete though, I'll elaborate on their purpose:

  • _i is the input used when create the moment object. It can be a string, a number, an array, or a Date object.

    However, if another moment object is passed in, the _i will be copied to that moments _i, and other properties will also be copied over. _i will never be a moment object.

    _i can also be undefined, in the case of creating the current moment with moment().

  • _d is the instance of the Date object that backs the moment object.

    If you are in "local mode", then _d will have the same local date and time as the moment object exhibits with the public API. The timestamps returned by getTime or valueOf will also match.

    If you are in "UTC mode", then _d will still have the same UTC date and time as the moment object exhibits with the public API. This may be confusing, as you'd need to look at getUTCDate and other UTC-based functions on _d in order to see them match. The timestamps will still match here as well.

    If you've changed the time zone offset, with the utcOffset, zone, or tz functions, then the _d value cannot stand alone. It must also consider if _offset is defined. If it is, then the timestamp backing the _d object has to first be adjusted by the amount of the offset. You can see this behavior in the implementation of the valueOf method here.

    Also, if you look at the string output of _d when a different offset or time zone has been applied, it will appear that _d is using the local time zone. However, that conversion to local time is simply a side effect of the toString function of the Date object. Moment does not use that result in its functions.

This is the behavior for these two fields as of the current version (2.10.6 as I'm writing this). However, there are other fields as well, and since these are internal fields, it's entirely possible the behavior could change in a future version. In particular, see issue #2616.


As a complement to @Matt's answer:

Checkout this result from the chrome's console:

date1 is a moment's valid object:

As you can see, ._d and ._i have different values. So you better use the format() function (as @Matt Johnson wrote) inside your source code.

Tags:

Momentjs