I have a problem with dates manipulation with Ionic and moment.js. I store some dates from a ion-datetime component :
{"year":2017,"month":7,"day":26,"hour":null,"minute":null,"second":null,"millisecond":null,"tzOffset":0}
And use moment.js to "humanize" date display :
let somedate = moment(some.date);
console.log('JSON date : ' + JSON.stringify(some.date) + ' resolved as : ' + somedate.format('DD/MM/YYYY'));
And got result :
Original JSON date : {"year":2017,"month":7,"day":26,"hour":null,"minute":null,"second":null,"millisecond":null,"tzOffset":0} resolved as : 26/08/2017
As you can consider, there's on month offset between original JSON date and moment display date...
What i'm missing ?
The Javascript month are in range of 0-11 ie January is 0, February is 1 and likewise, therefore it is moving you to the next month. Try subtracting 1 from month value, to get the correct month.
var some = {'date':{"year":2017,"month":6,"day":26,"hour":null,"minute":null,"second":null,"millisecond":null,"tzOffset":0} }; let somedate = moment(some.date); console.log('JSON date : ' + JSON.stringify(some.date) + ' resolved as : ' + somedate.format('DD/MM/YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Finally, with your answers, i resolved the problem with a conversion method that take the original JSON date format and return a Javascript Date object, using TypeScript :
private _JSONDateToDate(jsonDate: any){
if(typeof jsonDate == 'object')
return new Date(jsonDate.year, (parseInt(jsonDate.month) - 1), jsonDate.day);
return jsonDate;
}
I substract 1 month of the "month" property in order to have a correct Date object... then, i can manipulate it with moment.js
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.