PHP 中的日期比较

发布于 2024-11-28 06:56:23 字数 416 浏览 0 评论 0原文

我目前有一个日期作为 255 个字符的 VARCHAR 存储在我的 SQL 数据库中。我将此字符串声明为

   //within an object...
   $date = date(DATE_RFC822);

“现在”,稍后在编码中,我意识到我需要实际相互比较日期。我最初的、非常天真的尝试看起来有点像这样:

if(object_1->date > object_2->date){
 //do this that assumes that object_1 was created at a later date than object_2
}else{
 continue;
}

虽然这在同一天的不同时间都效果很好;一周后使用该代码开始显示出严重的错误。

I currently have a date that's being stored in my SQL database as a VARCHAR of 255 characters. I declared this string as

   //within an object...
   $date = date(DATE_RFC822);

Now, later on in the coding, I realise that I need to actually compare dates with each other. My initial, very naive attempt looked a little bit like this:

if(object_1->date > object_2->date){
 //do this that assumes that object_1 was created at a later date than object_2
}else{
 continue;
}

While this worked fine for different times of the same day; using the code a week later began to show significant bugs.

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

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

发布评论

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

评论(2

雨夜星沙 2024-12-05 06:56:24

strtotime() 将字符串转换为unix 时间(整数),可以轻松地与其他 unix 时间值进行比较。如果您运行的是 PHP 5.2.8 或更高版本,您还可以使用 DateTime 类相对容易比较(参见此问题了解更多信息)

strtotime() converts a string into unix time (an integer) which can easily be compared with other unix time values. If you are running PHP 5.2.8 or greater, you could also make use of the DateTime class which are relatively easy to compare (see this question for more info)

像极了他 2024-12-05 06:56:24

您无法相互比较 DATE_RFC822 格式的日期。您应该在 MySQL 中使用 Date 或 DateTime 字段,在 PHP 中使用 DateTime 或 Unix 时间戳。在 PHP DateTime 构造函数或 strtotime() 中使用 DATE_RFC822 字符串是安全的。 (不过,如果您在 MySQL 中使用 Date 或 DateTime,您还可以按日期排序和按日期搜索等)

PHP DateTime 对象可以像普通 PHP 变量一样相互比较,因此您可以执行 $date1 $date1 $date1 $date1 $date1 $date2 确定 $date1 是否在 $date2 之前。

You can't compare dates in DATE_RFC822 format with each other. You should use Date or DateTime fields in MySQL and DateTime or Unix timestamps in PHP. It's safe to use your DATE_RFC822 string in the PHP DateTime constructor or in strtotime(). (Still, if you use Date or DateTime in MySQL you can also sort by date and search by date, etc.)

PHP DateTime objects can be compared with each other like normal PHP variables, so you can do $date1 < $date2 to determine if $date1 is before $date2.

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