ApathyBear ApathyBear - 5 months ago 12
Javascript Question

UTC (elastic search) to MomentJs localtime

I am following an example fiddle that converts a UTC time to a local momentjs time.

Although my example isn't quite working correctly and I am attempting to understand why.

My ReactJS code executes the following function to display the proper time:

<p>Created Date: {(this.utcToLocalTime(result._source.created_date))}</p>


The function is as follows (ES6 code):

utcToLocalTime(utc_time) {
var localTime = moment.utc(utc_time).toDate()
console.log(localTime) // Tue Jun 21 2016 16:59:34 GMT-0700 (PDT)

var localTime_formatted = moment(localTime).format('YYYY-MM-DD HH:mm:ss')
console.log(localTime_formatted) //2016-06-21 16:59:34
return localTime_formatted
}


But I would like the time to show something local like
10:32 AM


How am I using MomentJS incorrectly?

Answer

As I understand your question, you want to parse the date from somehwat "normal" format to am/pm (12h system). To do so, just add an a at the end of your localTime_formatted Template like this:

utcToLocalTime(utc_time) {
    var localTime = moment.utc(utc_time).toDate()
    console.log(localTime) // Tue Jun 21 2016 16:59:34 GMT-0700 (PDT)

    var localTime_formatted = moment(localTime).format('YYYY-MM-DD HH:mm a')
    console.log(localTime_formatted) //2016-06-21 16:59:34
    return localTime_formatted
  }

I updated your fiddle here: http://jsfiddle.net/ya1h7zk6/

And here's a link to the momentjs parsing-documentation: http://momentjs.com/docs/#/parsing/

edit: by the way, you said "ES6 Code". Then please use let ( docs ) instead of var ;)