LOTUSMS
LOTUSMS

Reputation: 10240

How to display time with momentjs in react

I am running React Datepicker and I'm getting the dates correctly, but the times are eluding me.

In the constructor I set the time like this

constructor(props) {
        super(props);
        this.state = {
            startdate: moment('20180702', 'YYYYMMDD'),
            starttime: moment('1122', 'HHmm'),
        };
    }
}

Later in my component render I have (parameters are explained in the React DatePicker docs). This is not really of importance for my problem but I'm sharing it anyway. My problem is mostly on that moment instatiation in my constructor:

<DatePicker
    customInput={<StartTime />}
    popperClassName={classes.datepickerCalendar}
    isClearable
    selected={this.state.starttime}
    onChange={this.handleStartTimeChange}
    showTimeSelect
    showTimeSelectOnly
    timeIntervals={15}
    timeFormat="HH:mm"
    timeCaption="Time"
/>

The date is giving me an output of 07/020/2018 but the time is giving me some random or odd date as well, not an actual time. More specifically 11:22

I'm positive I am instatiating time incorrectly but I can't find an example in momentjs documentation.

How can I tell moment to display a time (i.e. 11:22)?

Upvotes: 2

Views: 562

Answers (1)

Chris
Chris

Reputation: 59491

Bear in mind that moment.js is a date library, so by doing moment('1122', 'HHmm') you are creating a new date, not an arbitrary "time". Since you don't specify day, month or year (on that particular line), moment assumes todays date. So this line will yeild the date: 2018/05/15 11:22.

So, if you want to pass the date 2018/07/02 11:22, you should do:

startdate: moment('20180702 1122', 'YYYYMMDD HHmm')

If your time seems off by a few hours, it's probably because the time will by default be printed in Zulu time (i.e GMT) which may not match your own timezone.


Demo:

var now =  moment('20180702 1122', 'YYYYMMDD HHmm');
console.log(now);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>

Upvotes: 1

Related Questions