英文:
My problem with get duration between 2 dates via moment
问题
这是两个相差20分钟的日期:
const a = moment.tz('Europe/Kiev');
const b = moment(item.sheduledAt);
console.log('我的当前时间: ', a.format('DD MMMM, HH:mm')); // 08 June, 09:42
console.log('预定时间: ', b.format('DD MMMM, HH:mm')) // 08 June, 10:00
console.log('差异: ', b.diff(a)) // 11832381
console.log('持续时间: ', moment.duration(b.diff(a)).asHours()) // 3.2867725
如果不指定时区,那么我的时间将显示不正确(根据实际服务器,差异是3小时)。但毕竟,我只是在比较2个日期,使用上面的format()
显示出20分钟的差异,3小时是从哪里来的,如何去除它们?
英文:
there are two dates with a difference of 20 minutes:
const a = moment.tz('Europe/Kiev');
const b = moment(item.sheduledAt);
console.log('my current time: ', a.format('DD MMMM, HH:mm')); // 08 June, 09:42
console.log('sheduled time: ', b.format('DD MMMM, HH:mm')) // 08 June, 10:00
console.log('diff: ', b.diff(a)) // 11832381
console.log('dur: ', moment.duration(b.diff(a)).asHours()) // 3.2867725
If you do not specify the time zone, then my time is shown incorrectly (according to the real server, it is 3 hours less). But after all, I'm just comparing 2 dates, which, when using format () above, show a difference of 20 minutes, where does 3 hours come from and how to remove them?
答案1
得分: 1
我遇到了一个问题,无论时区如何,都要正确设置并为每个人“相同”保存日期:
我有一个3步日期和时间选择器。首先,您使用日历('react-day-picker'),然后将小时和分钟设置为给定日期,看起来像这样:
(pickerData) => this.setState({sheduleDate: moment(pickerData).tz('Europe/Kiev')});
(e) => this.setState({sheduleDate: this.state.sheduleDate.set({h: e.target.value})});
(e) => this.setState({sheduleDate: this.state.sheduleDate.set({m: e.target.value})})
// 提交表单 - 伪代码
() => data['sheduledAt'] = moment(sheduleDate).unix() * 1000; // 这是我没有为 moment(sheduleDate) 指定 tz() 并获得服务器时间的地方,如果我理解正确的话
指定 tz() 后,日期将在所有时区下正确读取,即如果我有一个事件在20分钟内,那么在美国和乌克兰都是20分钟。
非常感谢 Justinas 的帮助!
英文:
I ran into a problem saving the date so that it is set correctly and is "the same" for everyone given the timezone:
I have a 3 step date and time picker. First you use the calendar('react-day-picker'), then set the hours and minutes to the given date, looks like this:
(pickerData) => this.setState({sheduleDate: moment(pickerData).tz('Europe/Kiev')});
(e) => this.setState({sheduleDate: this.state.sheduleDate.set({h: e.target.value})});
(e) => this.setState({sheduleDate: this.state.sheduleDate.set({m: e.target.value})})
// submit form - pseudocode
() => data['sheduledAt'] = moment(sheduleDate).unix() * 1000; // this is where I did not specify tz() for moment(sheduleDate) and got the server time, if I understand correctly
When specifying tz(), the date is then read correctly for all timezones, i.e. if I have an event in 20 minutes, then it is in 20 minutes in both the USA and Ukraine.
Big thanks to Justinas for help!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论