簡體   English   中英

PHP或JavaScript / jQuery中的未來timeago方法

[英]Future timeago method in PHP or JavaScript/jQuery

我正在瀏覽STO和網絡,但是沒有找到任何東西。

我正在尋找一種方法/功能來打印出可讀的未來時間表 ,例如:

  • 從現在開始的3個小時內
  • 從現在開始的1年

我將日期中的日期存儲到我的表格中的日期時間列中,我需要它來預測發布時剩余的時間等。

有沒有這樣的事情已經完成了? 如果是的話 - 請幫助。

這是我目前在PHP中的時間表

(我也有塞爾維亞 - 克羅地亞語 - 波斯尼亞語的這種方法的本地化版本)

public static function time_elapsed($ptime) {
    $etime = time() - $ptime;

    if ($etime < 1) {
        return '0 seconds';
    }

    $a = array(12 * 30 * 24 * 60 * 60 => 'year',
        30 * 24 * 60 * 60 => 'month',
        24 * 60 * 60 => 'day',
        60 * 60 => 'hour',
        60 => 'min',
        1 => 'sec'
    );

    foreach ($a as $secs => $str) {
        $d = $etime / $secs;
        if ($d >= 1) {
            $r = round($d);
            return $r . ' ' . $str . ($r > 1 ? 's' : '') . ' ago';
        }
    }
}

如果我理解你想要的東西,試試這個:

function time_elapsed($ptime) {
    $etime = $ptime - time();

    if ($etime < 1) {
        return '0 seconds';
    }

    $a = array(12 * 30 * 24 * 60 * 60 => 'year',
        30 * 24 * 60 * 60 => 'month',
        24 * 60 * 60 => 'day',
        60 * 60 => 'hour',
        60 => 'min',
        1 => 'sec'
    );

    foreach ($a as $secs => $text) {
        $d = $etime / $secs;
        if ($d >= 1) {
            $r = round($d);
            return "In " . $r . ' ' . $text . ($r > 1 ? 's' : '') . ' from now';
        }
    }
}

$time_elapsed = time_elapsed(time() + 36000); // prints In 10 hours from now 
var_dump($time_elapsed);

我建議使用http://momentjs.com/ 它具有您正在尋找的功能。 http://momentjs.com/docs/#/displaying/from/

例:

<script>
var my_date = moment('2014-07-07');
$("#date").val(start.from(my_date) + " from now"); // "in 5 days from now"
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM