Parse LocalDate json to moment in Angular

1k views Asked by At

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 ?

2

There are 2 answers

3
mplungjan On BEST ANSWER

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>

6
alexKhymenko On

what you need to do is

 moment().minute(this.car.minute.overview.minute).second(this.car.minute.overview.second).hours(this.car.minute.overview.hour) 

and so on for information read https://momentjs.com/docs/#/get-set/