简体   繁体   English

Laravel Order通过带时区的日期时间

[英]Laravel orderBy datetime with timezone

I'm ordering a list of events by datetime which works fine, however a problem occurs when some items have a timezone applied to them - they don't order correctly. 我正在按日期时间排序事件列表,效果很好,但是当某些项目应用了时区时会发生问题-它们的排序不正确。 Eg 例如

Event 1 - Ends 20th June 2018 at 15:00:00 (Europe/London) 活动1-结束于2018年6月20日15:00:00(欧洲/伦敦)

Event 2 - Ends 20th June 2018 at 13:00:00 (US/Eastern) 活动2-于2018年6月20日13:00:00(美国/美国东部)结束

When these are ordered by date ascending 'Event 2' shows BEFORE 'Event 1' because timezone is ignored (when in real time it's 2 hours later) 如果按日期升序排列,则“事件2”显示在“事件1”之前,因为会忽略时区(实时时间是2小时后)

I have tried using a mutator in Laravel to convert both datetimes and timezones to timestamps: 我曾尝试在Laravel中使用mutator将日期时间和时区都转换为时间戳:

 public function getDatetimeTzSecondsAttribute()
{
    $newDate = new Carbon($this->attributes['date_finish'], $this->attributes['timezone']);

    return $newDate->toTimeString();
}

But understand this won't work as mutators are processed after results have been fetched. 但是请理解,由于在获取结果后处理了变异体,因此这是行不通的。 I am using pagination for results - whats the best way to order this data via the query builder/eloquent if possible? 我正在使用分页来显示结果-如果可能的话,通过查询生成器/雄辩的命令排序数据的最佳方法是什么?

If it helps anyone I came up with quite a simple solution after hours of brainache... 如果可以帮助任何人,经过数小时的头痛,我想出了一个非常简单的解决方案...

Use the MySQL 'CONVERT_TZ' function to change from timezone set to UTC: 使用MySQL的'CONVERT_TZ'函数将时区设置为UTC:

->selectRaw('*, CONVERT_TZ(date_finish, timezone, \'UTC\') AS date_finish_converted ')

Then order by the new converted date column (if set) along with the standard date column: 然后,按照新的转换日期列(如果已设置)和标准日期列进行排序:

->orderByRaw('COALESCE(date_finish_converted, date_finish), date_finish');

Genius! 天才! :) :)

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

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