English 中文(简体)
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:

  • Today, 6:00pm
  • Tomorrow, 12:30pm
  • Wednesday, 4:00pm
  • Next friday, 11:00am

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

An example of converting UNIX timestamp to your format:

$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:

$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:

$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.

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. 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() would convert the epoch time to the local server time... this was something I don t want on my projects.

/**
 * 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

The above code is in codeigniter format, but you can just convert it to a SELECT statement for MYSQL

$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.

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 ;

        }




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签