简体   繁体   English

人类可读的,当前时间敏感的日期和时间格式的PHP

[英]Human-readable, current time sensitive date and time formatting in PHP

Is there a painless way to convert unix timestamps, MySQL timestamps, MySQL datetimes (or any other standard date and time format) into strings in the following form: 是否可以通过以下方式轻松地将unix时间戳,MySQL时间戳,MySQL日期时间(或任何其他标准日期和时间格式)转换为字符串:

  • Today, 6:00pm 今天下午6:00
  • Tomorrow, 12:30pm 明天下午12:30
  • Wednesday, 4:00pm 星期三4:00 pm
  • Next friday, 11:00am 下周五,上午11:00

I'm not sure what to call these - I guess conversational-style, current time sensitive date formats? 我不确定该怎么称呼-我猜是会话式的当前时间敏感日期格式吗?

As best I can tell, there is no native function for this. 尽我所能告诉我们,没有本机功能。 I have created (the start of) a function to do what you are wanting. 我已经创建了一个函数(开始)来执行您想要的操作。

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 );
}

Hope that helps. 希望能有所帮助。

You should read the docs for strftime and strtotime 您应该阅读有关strftimestrtotime的文档

An example of converting UNIX timestamp to your format: 将UNIX时间戳转换为格式的示例:

$time = time(); // UNIX timestamp for current time
echo strftime("%A, %l:%M %P"); // "Thursday, 12:41 pm"

To get a MySQL datetime value, assuming it comes out of the database as "2010-07-15 12:42:34", try this: 要获取MySQL日期时间值(假设它从数据库中出来为“ 2010-07-15 12:42:34”),请尝试以下操作:

$time = "2010-07-15 12:42:34";
echo strftime("%A, %l:%M %P"); // "Thursday, 12:42 pm"

Now, in order to print the word "today" instead of the day name you will have to do some additional logic to check if the date is today: 现在,为了打印单词“ today”而不是日期名称,您将必须执行一些附加的逻辑来检查日期是否是今天:

$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);
}

The strtotime shoule be useful for that. strtotime应该对此有用。

Example: 例:

echo date('d, h:i:sa', strtotime($date_orig));

PHP date funcs are kind of messy because they have so many different ways, and even new classes were built over the old ones. PHP日期函数有点麻烦,因为它们有许多不同的方式,甚至新的类都是在旧的类的基础上构建的。 For that type of formatting, what I call human-friendly formatting, you're going to have to write your own function that does it. 对于这种格式,我称之为对人类友好的格式,您将必须编写自己的函数来执行此操作。

For conversion, you can use strtotime() as mentioned, but if you're dealing with epoch times and need utc GMT times, heres some functions for that. 对于转换,您可以使用提到的strtotime(),但是如果您正在处理纪元时间并且需要utc GMT时间,则这里提供一些函数。 strtotime() would convert the epoch time to the local server time... this was something I don't want on my projects. strtotime()会将纪元时间转换为本地服务器时间...这是我不需要的项目。

/**
 * Converts a GMT date in UTC format (ie. 2010-05-05 12:00:00)
 * Into the GMT epoch equivilent
 * The reason why this doesnt work: strtotime("2010-05-05 12:00:00")
 * Is because strtotime() takes the servers timezone into account
 */
function utc2epoch($str_date)
{
    $time = strtotime($str_date);
    //now subtract timezone from it
    return strtotime(date("Z")." sec", $time);
}

function epoch2utc($epochtime, $timezone="GMT")
{
    $d=gmt2timezone($epochtime, $timezone);
    return $d->format('Y-m-d H:i:s');
}

If you are pulling this type of data out of your database 如果您要从数据库中提取此类数据

$time = "2010-07-15 12:42:34";

then do this 然后做这个

$this->db->select('DATE_FORMAT(date, "%b %D %Y")AS date');

Look here for info to display your data any way you want in human form 在此处查找信息,以您想要的任何形式以人类形式显示数据

http://www.w3schools.com/SQL/func_date_format.asp http://www.w3schools.com/SQL/func_date_format.asp

The above code is in codeigniter format, but you can just convert it to a SELECT statement for MYSQL 上面的代码是codeigniter格式,但是您可以将其转换为MYSQL的SELECT语句

$query = "SELECT `title`,`post`, DATE_FORMAT(date, "%a, %d %b %Y %T") AS date FROM `posts` LIMIT 0, 8 ";

You will want to change the %a letters to fit your needs. 您将需要更改%a字母以适合您的需求。

you will get exact result::
output // 28 years 7 months 7 days


        function getAge(dateVal) {
            var
                birthday = new Date(dateVal.value),
                today = new Date(),
                ageInMilliseconds = new Date(today - birthday),
                years = ageInMilliseconds / (24 * 60 * 60 * 1000 * 365.25 ),
                months = 12 * (years % 1),
                days = Math.floor(30 * (months % 1));
            return Math.floor(years) + ' years ' + Math.floor(months) + ' months ' + days + ' days';

        }

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

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