momentjs for only time value

11,591

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']);
Share:
11,591

Related videos on Youtube

Heidel
Author by

Heidel

Updated on June 04, 2022

Comments

  • Heidel
    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 like 2018-05-22 14:45 or if it contains only date like 2018-05-22. The problem is sometimes component.props.data.value contains only time like 14:45, so moment(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?