首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP中可读的、当前时间敏感的日期和时间格式设置

PHP中可读的、当前时间敏感的日期和时间格式设置
EN

Stack Overflow用户
提问于 2010-07-15 19:34:24
回答 6查看 2.6K关注 0票数 2

是否有一种以下列形式将unix时间戳、MySQL时间戳、MySQL日期时间(或任何其他标准日期和时间格式)转换为字符串的无痛方法:

今日6:00pm

  • Tomorrow,12:30pm

  • Wednesday,4:00
  • 下周五上午11:00

我不知道如何称呼这些--我猜--对话式的,当前时间敏感的日期格式?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-07-15 20:39:03

据我所知,这里没有本机函数。我已经创建了一个函数来做你想做的事情。

代码语言:javascript
复制
function timeToString( $inTimestamp ) {
  $now = time();
  if( abs( $inTimestamp-$now )<86400 ) {
    $t = date('g:ia',$inTimestamp);
    if( date('zY',$now)==date('zY',$inTimestamp) )
      return 'Today, '.$t;
    if( $inTimestamp>$now )
      return 'Tomorrow, '.$t;
    return 'Yesterday, '.$t;
  }
  if( ( $inTimestamp-$now )>0 ) {
    if( $inTimestamp-$now < 604800 ) # Within the next 7 days
      return date( 'l, g:ia' , $inTimestamp );
    if( $inTimestamp-$now < 1209600 ) # Within the next 14, but after the next 7 days
      return 'Next '.date( 'l, g:ia' , $inTimestamp );
  } else {
    if( $now-$inTimestamp < 604800 ) # Within the last 7 days
      return 'Last '.date( 'l, g:ia' , $inTimestamp );
  }
 # Some other day
  return date( 'l jS F, g:ia' , $inTimestamp );
}

希望这能有所帮助。

票数 4
EN

Stack Overflow用户

发布于 2010-07-15 19:49:40

您应该阅读strftimestrtotime的文档。

将UNIX时间戳转换为您的格式的示例:

代码语言:javascript
复制
$time = time(); // UNIX timestamp for current time
echo strftime("%A, %l:%M %P"); // "Thursday, 12:41 pm"

要获得一个MySQL日期时间值,假设它从数据库中得到为"2010-07-15 12:42:34",请尝试如下:

代码语言:javascript
复制
$time = "2010-07-15 12:42:34";
echo strftime("%A, %l:%M %P"); // "Thursday, 12:42 pm"

现在,为了打印单词“今天”而不是日期名称,您必须执行一些额外的逻辑来检查日期是否为今天:

代码语言:javascript
复制
$time = "2010-07-15 12:42:34";
$today = strftime("%Y-%m-%d");

// compare if $time strftime's to the same date as $today
if(strftime("%Y-%m-%d", $time) == $today) {
  echo strftime("Today, %l:%M %P", $time);
} else {
  echo strftime("%A, %l:%M %P", $time);
}
票数 1
EN

Stack Overflow用户

发布于 2010-07-15 19:38:52

strtotime应该在这方面很有用。

示例:

代码语言:javascript
复制
echo date('d, h:i:sa', strtotime($date_orig));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3259261

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档