Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to get the input provided to momentjs

Is there any function to get the input that was provided to moment()

In the example below, inputDate becomes null.

var date = moment("invalid date");
if(!data.isValid()){
  return { message: "Invalid date", inputDate: date }
}

I can access the input using internals i.e. date._i but was wondering if there's any function that would return the input provided to moment constructor.

like image 756
Sami Avatar asked Dec 20 '17 13:12

Sami


People also ask

How do I get time from MomentJS?

You can directly call function momentInstance. valueOf(), it will return numeric value of time similar to date. getTime() in native java script.

What is moment () Unix ()?

The moment(). unix() function is used to get the number of seconds since the Unix Epoch.

How do I get current year in MomentJS?

year() method is used to get or set the year of the Moment object. The year value that can be set has a range from -270,000 to 270,000. Syntax: moment().

How do you get moments from the day?

The moment(). day() method is used to get or set the day of week of the Moment object. The day of the week can have a value between 0 and 6, where 0 denotes Sunday and 6 denotes Saturday. A value outside this range will make it go to the previous or upcoming weeks.


1 Answers

You can use creationData()

After a moment object is created, all of the inputs can be accessed with creationData() method:

moment("2013-01-02", "YYYY-MM-DD", true).creationData() === {
    input: "2013-01-02",
    format: "YYYY-MM-DD",
    locale: Locale obj,
    isUTC: false,
    strict: true
}

Here a live example:

var date = moment("invalid date", moment.ISO_8601);
console.log(date.creationData().input);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script>

As a side note:

  • I've used moment.ISO_8601 in my snippet to prevent Deprecation Warning, as shown here.
  • Something quite similar was asked (but not a duplicate) was asked here.
like image 127
VincenzoC Avatar answered Nov 14 '22 20:11

VincenzoC