Home > Back-end >  Passing correct value to moment.js `toDate() function`
Passing correct value to moment.js `toDate() function`

Time:01-21

In my timepicker component in my react-native app I need to pass a value into moment's toDate() function, because that's the format the component requires.

The value I have is a clock value, coming in as a string, such as "14:23".

My question is, how can I take that clock string value, attach it to a date, and then format it in such a way that I can pass that all in as the value for val to be passed in here:

 this.value = moment(val).toDate();

I tried this:

const val = "14:24"

const m = moment(`2022-02-19:${val}`);
console.log('isValid: ', m.isValid()); // false

But this fails.

But, for that matter, so does this:

const m = moment("2011-10-10T10:20:90");
console.log('isValid: ', m.isValid()); // false

So I guess that's not surprising, and suggests there's something I'm not understanding here. Bottom line how can I format a value, with a string value like "14:24", and then pass it to moment's toDate() function?

  this.value = moment(val).toDate();

CodePudding user response:

Moment has a formatter that formats then parses this string into a JavaScript date. The current format you're using is not the standard ISO8601 format YYYY-MM-DDTHH:mm:ssZ, so moment will not natively support it, because you're using a : symbol after the day, not the letter "T".

You can easily get the desired effect by changing your code like so:

const m = moment(`2022-02-19T${val}`);

Alternatively, you can change moments defaultFormatter to support whatever format you want. To do this, you can simply call it like this:

moment.defaultFormat = "YYYY-MM-DD:HH:mm"

Or simply explicitly pass the formatter into moment alongside the datestring like this:

const m = moment(`2022-02-19:${val}`, "YYYY-MM-DD:HH:mm").toDate()
  •  Tags:  
  • Related