简体   繁体   中英

PHP Intl library and human readable time span

I'm using PHP Intl library to format dates, numbers and so on. Now I have to show a time span in human readable string, for example:

1day, 1hour, 10 minutes, 14s

or in compact way:

1d 1s 10m 14s

or in supercompact way:

1d 1.10:14

Is there any way to do this using the build in Intl library without gettext? If no, I can format the timespan with a custom function, but can I get at least the names ('day', or 'd') in the correct locale from IntlDateFormatter?

Yes, answer for your question is DateInterval . According to documentation you can use it this way:

$pastDate = new DateTime('2015-09-01 15:00:00');
$today = new DateTime();

//calculate interval and returns DateInterval object
$timeSpan = $today->diff($pastDate); 

//now we'll format it
echo $timeSpan->format('%a day, %h hour, %i minutes, %ss').PHP_EOL;
echo $timeSpan->format('%ad %hh %im %ss').PHP_EOL;
echo $timeSpan->format('%ad %h.%i:%s').PHP_EOL;

The result will be:

100 day, 9 hour, 55 minutes, 12s

100d 9h 55m 12s

100d 9.55:12

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