简体   繁体   English

Ionic 2 JSON日期和moment.js麻烦

[英]Ionic 2 JSON dates and moment.js trouble

I have a problem with dates manipulation with Ionic and moment.js. 我在使用Ionic和moment.js进行日期操作时遇到问题。 I store some dates from a ion-datetime component : 我从ion-datetime组件存储一些日期:

{"year":2017,"month":7,"day":26,"hour":null,"minute":null,"second":null,"millisecond":null,"tzOffset":0}

And use moment.js to "humanize" date display : 并使用moment.js来“人性化”日期显示:

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... 您可以考虑,原始JSON日期和时刻显示日期之间存在月份偏移量...

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. Javascript月份的范围是0到11,即一月是0,二月是1,同样,因此它会将您移至下个月。 Try subtracting 1 from month value, to get the correct month. 尝试从月份值中减去1,以获得正确的月份。

 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 : 最后,根据您的回答,我使用转换方法解决了问题,该方法采用原始JSON日期格式并使用TypeScript返回Javascript Date对象:

  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 我减去“ month”属性的1个月以拥有正确的Date对象...然后,我可以使用moment.js对其进行操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM