在 PHP 中按任意日期搜索数据库

发布于 2024-08-26 00:45:41 字数 570 浏览 2 评论 0原文

假设您有一个用 PHP 构建的带有 MySQL 数据库后端的消息系统,并且您希望支持使用任意日期字符串搜索消息。

该数据库包括一个消息表,其中“date_created”字段表示为日期时间。

用户接受的任意日期字符串的示例应该反映 strtotime 接受的那些字符串。

对于以下示例,在 2010 年 3 月 21 日执行的搜索:

“2009 年 1 月 26 日”将返回 2009-01-26 00:00:00 到 2009-01-27 00:00:00 之间的所有邮件
“March 8”将返回 2010-03-08 00:00:00 和 2010-01-26 00:00:00 之间的所有消息
“上周”将返回 2010-03-14 00:00:00 和 2010-03-21 018:25:00 之间的所有消息
“2008”将返回 2008-01-01 00:00:00 和 2008-12-31 00:00:00 之间的所有消息

我开始使用 date_parse,但变量的数量增长很快。我想知道我是否在重新发明轮子。

有没有人有一个建议可以作为通用解决方案,或者可以捕获大多数可能的输入字符串?

Suppose you have a messaging system built in PHP with a MySQL database backend, and you would like to support searching for messages using arbitrary date strings.

The database includes a messages table, with a 'date_created' field represented as a datetime.

Examples of the arbitrary date strings that would be accepted by the user should mirror those accepted by strtotime.

For the following examples, searches performed on March 21, 2010:

"January 26, 2009" would return all messages between 2009-01-26 00:00:00 and 2009-01-27 00:00:00
"March 8" would return all messages between 2010-03-08 00:00:00 and 2010-01-26 00:00:00
"Last week" would return all messages between 2010-03-14 00:00:00 and 2010-03-21 018:25:00
"2008" would return all messages between 2008-01-01 00:00:00 and 2008-12-31 00:00:00

I began working with date_parse, but the number of variables grew quickly. I wonder if I am re-inventing the wheel.

Does anyone have a suggestion that would work either as a general solution or one that would capture most of the possible input strings?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黒涩兲箜 2024-09-02 00:45:41

尝试 strtotime 它非常擅长猜测日期正确。

  • “上周”
  • “下周”
  • “+15 天”
  • “上周二”
  • “10 月 31 日”
  • 等。

Try strtotime It is VERY good at guessing dates correctly.

  • "Last week"
  • "Next Week"
  • "+15 days"
  • "Last tuesday"
  • "October 31st"
  • etc.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文