douju6542 2019-07-27 15:22
浏览 113

比较日期与时区得出错误的评价

I have a service where users can create events and participate in said events. On event creation, users can assign the start, end dates and times and then fill in the timezone that the event is going to take place in. Upon completion they can invite other users to participate in the event.

When members visit the event page a piece of backend logic checks current time against the event's start time. If the current time (of the user/user's timezone) is within the start and end time of the event, the user will then be able to attend the event (giving them access to a hallway page where they can video conference).

My issue is with the comparison of dates with different timezones. I'm saving all the dates with the default UTC timezone. Example of a start date being

 date: 2019-07-27 11:00:00.0 UTC (+00:00)

And then comparing $now with it. $now being the below for example

date: 2019-07-27 18:11:18.747797 Asia/Beirut (+03:00)

$now is being assigned as such

$now = Carbon::now()->tz($userProfile->timezone->key);

But when I do a comparison such as

$now->lte($event->ends_at)

I'm getting a wrong evaluation where even if $now is later than $event->ends_at it is still evaluating as true. Is it a matter of evaluating dates with different timezones?

  • 写回答

1条回答 默认 最新

  • doutui839638 2019-08-06 15:36
    关注

    lte()rely on<=` PHP operator as PHP do it for DateTime objects and it compares naively only numbers. So you should compare only dates in the same timezone (ideally on UTC dates).

    $now->copy()->tz('UTC')->lte($event->ends_at->copy()->tz('UTC'))
    

    The ->copy() calls are not needed if you're working with CarbonImmutable (recommended).

    评论

报告相同问题?

悬赏问题

  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决