简体   繁体   中英

how to convert time format from number to string?

i fetched from created field date and time like this format 2011-3-10 17:26:50 and i want to convert to this format March 13, 2010 how can i do this with php or cakephp 1.3

     <?php

  $i = 0;
foreach($articles as $$article ):

                 ?>
                <tr>
                    <td><?php echo $article['Article']['title']; ?></td>
                    <td><?php echo $article['Article']['created'];;?></td>
                </tr>
                <?php endforeach; ?>

I presume you mean "fetched" as in retrieving from MySQL. The simplest/quickest (but also the most like to blow up and kick your dog) is to simply do

$timestamp = strtotime($date_from_database);
$formatted = date('F j, Y', $timestamp);

PHP has a function strtotime($string) , that will take dates/time strings in a variety of formats (including MySQL's datetime format) and convert it to a Unix timestamp integer (number of seconds since 1970-01-01 00:00:00 UTC ). You can then use date('F j, Y', $time) to convert that integer into whatever string representation you want, using the tokens found here

Two additional considerations are localization and timezone awareness. I won't go into the first since it doesn't seem like you need it, but where timezone matters, it can be easier to use PHP's DateTime classes, which you can read about [here] . Here's an example:

<?php

// for example, if you're storing times in UTC in your DB
$dbTimezone = new DateTimeZone('UTC');

// we'll use this for displaying times in the user's timezone.
// for example, my timezone:
$displayTimezone = new DateTimeZone('America/Toronto');

foreach ($articles as $article):
    // Create a timezone-aware DateTime object from your article's creation date
    $dt = new DateTime($article['Article']['create'], $dbTimezone);
    $dt->setTimezone($displayTimezone);
    echo $dt->format('F j, Y');
endforeach;

something like this ? I'm guessing your datetime format. you may need to adjust it.

echo date('F d, Y',date_create_from_format('Y-n-d h:i:s','2011-3-10 17:26:50'));

date_create_from_format

This will solve it:

$date = date_create_from_format('Y-m-j H:i:s', $article['Article']['created']);
echo date_format($date, 'F d, Y');

You could easily use the Cakephp Time Helper.

//Add to appcontroller or articles_controller
var $helpers = array('Time');

//Add this to view file
echo $this->Time->niceShort($article['Article']['created']); 

Besides niceShort there are more options that might fit your needs better. Check CakePHP documentation.

Thanks,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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