Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php strtotime reverse

Tags:

php

strtotime

Is there some function timetostr in php that will output today/tomorrow/next sunday/etc. from a given timestamp? So that timetostr(strtotime(x))=x

like image 348
prongs Avatar asked Dec 25 '11 13:12

prongs


People also ask

How convert seconds to hours minutes and seconds in PHP?

PHP Code: <? php function convert_seconds($seconds) { $dt1 = new DateTime("@0"); $dt2 = new DateTime("@$seconds"); return $dt1->diff($dt2)->format('%a days, %h hours, %i minutes and %s seconds'); } echo convert_seconds(200000).


1 Answers

This might be useful for people coming here.

/**
 * Format a timestamp to display its age (5 days ago, in 3 days, etc.).
 *
 * @param   int     $timestamp
 * @param   int     $now
 * @return  string
 */
function timetostr($timestamp, $now = null) {
    $age = ($now ?: time()) - $timestamp;
    $future = ($age < 0);
    $age = abs($age);

    $age = (int)($age / 60);        // minutes ago
    if ($age == 0) return $future ? "momentarily" : "just now";

    $scales = [
        ["minute", "minutes", 60],
        ["hour", "hours", 24],
        ["day", "days", 7],
        ["week", "weeks", 4.348214286],     // average with leap year every 4 years
        ["month", "months", 12],
        ["year", "years", 10],
        ["decade", "decades", 10],
        ["century", "centuries", 1000],
        ["millenium", "millenia", PHP_INT_MAX]
    ];

    foreach ($scales as list($singular, $plural, $factor)) {
        if ($age == 0)
            return $future
                ? "in less than 1 $singular"
                : "less than 1 $singular ago";
        if ($age == 1)
            return $future
                ? "in 1 $singular"
                : "1 $singular ago";
        if ($age < $factor)
            return $future
                ? "in $age $plural"
                : "$age $plural ago";
        $age = (int)($age / $factor);
    }
}
like image 101
rich remer Avatar answered Oct 01 '22 21:10

rich remer