0

我查看了 PHP 日期手册,但找不到任何有关它的文档。我在荷兰网站http://marktplaats.nl上找到了它。如果您查看此网址,您可以看到“Vandaag”,这意味着“今天”,他们是如何做到的?

我现在拥有的代码:

<?= date ("d M 'y",strtotime($row['aangeboden-sinds'])); ?>
4

2 回答 2

0

很有可能这是在 SQL 中完成的,而不是在应用程序代码中。以下是在 PostgreSQL 中如何做到这一点。(查询似乎在 MySQL 5.6 中无需修改即可工作,这让我有点惊讶。)

create table test (
  test_id integer primary key,
  created_at timestamp not null default current_timestamp
  );

insert into test values 
(1, current_timestamp),
(2, current_timestamp - interval '1' day),
(3, current_timestamp - interval '10' day);

使用 CASE 语句和简单的日期算术来做几乎任何你想做的事情。

select test_id,
       case current_date - cast(created_at as date)
           when 0 then 'Added today'
           when 1 then 'Added yesterday'
           else 'Added some time ago'
       end as when_added
from test
order by created_at desc, test_id asc

TEST_ID  WHEN_ADDED
--
1        Added today
2        Added yesterday
3        Added some time ago

当 you 时order by created_at desc,您的数据自然会按显示顺序返回(不考虑您的应用程序可能需要的任何其他列),而在 php 中,您只需要显示“when_added”列。您不需要在 php.ini 中进行任何操作。

于 2013-07-23T15:56:29.020 回答
0

它可能只是 UI 逻辑中的一个简单条件。数据库本身只存储发生某事的日期,然后在显示逻辑中它们可能具有类似(伪代码)的内容:

if (currentDate - storedDate < 1)
    echo "Today";
else if (currentDate - storedDate < 2)
    echo "Yesterday";
else
    echo storedDate;

您可以添加一些额外的逻辑来解释午夜的翻转(至少对于特定时区,除非您还有用户的时区信息来个性化数学),而不是直接的 24 小时比较,但最终它是实际上仍然只是显示逻辑中的一个条件,对于数据的存储方式没有什么特别的。

于 2013-07-23T13:41:35.033 回答