momentjs for only time value
You can use moment(String, String[])
, as the docs says:
If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.
This is the same as String + Format, only it will try to match the input to multiple formats.
Your first line of code could be like the following:
let dateAndTime = moment(component.props.data.value, [moment.ISO_8601, 'HH:mm']);
Related videos on Youtube
Heidel
Updated on June 04, 2022Comments
-
Heidel almost 2 years
I use momentjs to work with date and time
let dateAndTime = moment(component.props.data.value, moment.ISO_8601); let date = '', time = ''; if (dateAndTime) { if (moment(dateAndTime, 'YYYY-MM-DD', true).isValid()) { date = moment(dateAndTime).format('YYYY-MM-DD'); } if (moment(dateAndTime, 'HH:mm', true).isValid()) { time = moment(dateAndTime).format('HH:mm'); } }
this code works just fine if
component.props.data.value
contains date and time like2018-05-22 14:45
or if it contains only date like2018-05-22
. The problem is sometimescomponent.props.data.value
contains only time like14:45
, somoment(component.props.data.value, moment.ISO_8601)
doesn't create moment object and code below doesn't execute. Is there any way to handle case only for time?