Search code examples
jsonangularmomentjslocaldate

Parse LocalDate json to moment in Angular


I'm receiving LocalDate from backend in JSON witch looks like

{"dayOfMonth":25,
 "dayOfWeek":"TUESDAY",
 "dayOfYear":206,
 "month":"JULY",
 "monthValue":7,
 "year":2017,
 "hour":0,
 "minute":0,
 "nano":0,
 "second":0,
 "chronology":{"id":"ISO","calendarType":"iso8601"}}}

and I want to parse it to a moment js object

 moment(this.car.overview).format();

Invalid date

console.log(moment().format(car.overview));

ERROR TypeError: format.replace is not a function

Anyone knows how to get a valid moment object from this JSON ?


Solution

  • You mean this?

    PS: If you receive a JSON string you need to JSON.parse it first

    var overview = {
      "dayOfMonth": 25,
      "dayOfWeek": "TUESDAY",
      "dayOfYear": 206,
      "month": "JULY",
      "monthValue": 7,
      "year": 2017,
      "hour": 0,
      "minute": 0,
      "nano": 0,
      "second": 0,
      "chronology": {
        "id": "ISO",
        "calendarType": "iso8601"
      }
    }
    
    console.log(
      moment({
        y: overview.year,
        M: overview.monthValue - 1,
        d: overview.dayOfMonth,
        h: overview.hour,
        m: overview.minute,
        s: overview.second,
        ms: overview.nano
      })
    )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>