Penggunaan fungsi strtotime()

Bagaimana cara menggunakan fungsi strtotime() untuk menampilkan seperti contoh "Post ini diterbitkan 3 hari yang lalu".

avatar fizaahmad
@fizaahmad

8 Kontribusi 2 Poin

Diperbarui 4 tahun yang lalu

1 Jawaban:

<pre>function time_elapsed_string($datetime, $full = false) { $now = new DateTime; $ago = new DateTime($datetime); $diff = $now-&gt;diff($ago);

$diff-&amp;gt;w = floor($diff-&amp;gt;d / 7);
$diff-&amp;gt;d -= $diff-&amp;gt;w * 7;

$string = [
    &#039;y&#039; =&amp;gt; &#039;year&#039;,
    &#039;m&#039; =&amp;gt; &#039;month&#039;,
    &#039;w&#039; =&amp;gt; &#039;week&#039;,
    &#039;d&#039; =&amp;gt; &#039;day&#039;,
    &#039;h&#039; =&amp;gt; &#039;hour&#039;,
    &#039;i&#039; =&amp;gt; &#039;minute&#039;,
    &#039;s&#039; =&amp;gt; &#039;second&#039;,
];

foreach ($string as $k =&amp;gt; &amp;amp;$v) {
    if ($diff-&amp;gt;$k) {
        $v = $diff-&amp;gt;$k . &#039; &#039; . $v . ($diff-&amp;gt;$k &amp;gt; 1 ? &#039;s&#039; : &#039;&#039;);
    } else {
        unset($string[$k]);
    }
}

if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(&#039;, &#039;, $string) . &#039; ago&#039; : &#039;just now&#039;;

}

echo "Post ini diterbitkan " , time_elapsed_string('2020-10-28 00:00:00');</pre>

avatar rezanotalive
@rezanotalive

2 Kontribusi 0 Poin

Dipost 4 tahun yang lalu

Login untuk ikut Jawaban