且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在codeigniter中将时间戳转换为日期

更新时间:2023-01-22 14:34:42

为什么不只使用PHP的日期函数?

  public函数time_convert($ timestamp){
返回日期('l Y / m / d H:i',$ timestamp);
}

对于不同的时区,请使用DateTime对象:

 公共函数time_convert($ timestamp,$ timezone ='UTC'){
$ datetime = new DateTime($ timestamp,new DateTimeZone($ timezone) );
返回$ datetime-> format(’l Y / m / d H:i’);
}

这应该可行。注意:我认为您至少需要TimeZone类的PHP版本5.20。


I want to convert 1373892900000 to Monday 2013/07/15 8:55 AM in Codeigniter.

However, I keep receiving a totally different result by converting the timestamp using the function i have written, please note:I need to change the dates according to different timezones, that is why I want to write it this way:

public function time_convert($timestamp){

        $this->load->helper('date');

        date_default_timezone_set('UTC');

        $daylight_saving = TRUE;
        $timezone = "UM4"; //toronto or new york timezone
        $time = gmt_to_local($timestamp, $timezone, $daylight_saving);

        $final_time = standard_date('DATE_RFC822', $time);  
        return $final_time;

    }

Result from the above function is: Sat, 08 Dec 06 01:40:00 +0000

And if I don't put date_default_timezone_set('UTC'); in the above function, I get this date instead Sat, 08 Dec 06 02:40:00 +0100. My codeigniter seems to default the timezone to Europe/Berlin.

Can anyone please help me correct any of the mistakes I might have made?

Why not just use PHP's date function?

public function time_convert($timestamp){
   return date('l Y/m/d H:i', $timestamp);
}

For different timezones use a DateTime object:

public function time_convert($timestamp, $timezone = 'UTC'){
    $datetime = new DateTime($timestamp, new DateTimeZone($timezone));
    return $datetime->format('l Y/m/d H:i');
}

Think that should work. Note: I tihnk you need at least PHP version 5.20 for the TimeZone class.