2016-08-15 113 views
1

添加小时时间戳类型字段我想一个小时在PHP中添加时间戳格式如何从MySQL数据库

这是我一直想这整个时间:在我的数据库

我有一个名为ts的字段,如时间戳(它是一个可捕获CURRENT_TIMESTAMP的时间戳字段)。 然后我在codeigniter的foreach显示我的结果。在我的结果中,我回显ts变量,但它捕获的小时数是错误的,所以我想改变时间并添加2小时。

这是我曾尝试代码:

foreach($row as $reg){ 
    $timestamp = $reg->ts; 
    $date = new DateTime($timestamp); 
    $nTime = $date->modify('+2 hour'); 
    echo $nTime; 
} 

它给了我这个错误:在使用DateTime对象的

A PHP Error was encountered Severity: 4096Message: Object of class DateTime could not be converted to stringFilename: libraries/Table.phpLine Number: 353

+0

你应该解决这个插入,也许? – Tpojka

回答

2

小错误。

foreach($row as $reg){ 
    $date = new DateTime(); 
    $date->setTimestamp($reg->ts); 
    $date->modify('+2 hour'); 
    echo $date->format('Y-m-d H:i:s'); 
} 

您可能想要为日期和时间使用不同的格式!添加时间的

+0

它给我2小时的时间,而不是'$ timestamp'的时间 – learningbyexample

+0

美国/墨西哥城市时区 – learningbyexample

+0

CDT(中央夏令时)UTC/GMT -5小时 – learningbyexample

2

实施例迄今

$nTime = date("Y-m-d H:i:s", strtotime('+2 hours')) 

Notedate("Y-m-d H:i:s") used to set TIMESTAMP manually


你的情况

foreach($row as $reg){ 
    $timestamp = date_create('2016-08-16 01:30:00'); 
    $date = new DateTime(date_format($timestamp,"Y/m/d H:i:s")); // 2016-08-16 01:30:00 
    $nTime = date_modify($date, "+2 hours"); 
    echo date_format($nTime,"Y/m/d H:i:s"); // Output will be 2016-08-16 03:30:00 
} 

输出

enter image description here


你提到“的变量,但它抓住了小时是错误的”,在你的问题。这可能是你必须设置date_default_timezone_set("Country/City")

+1

为什么你会尝试用完全不同的答案来回答这个问题? OP的问题只是一个简单的方法在日期时间类中使用 – Ghost

+0

@Ghost现在似乎我与他的问题有关。感谢您的提示 –

+0

您可能想要测试DateTime功能。它不工作。您无法使用时间戳初始化DateTime对象! – RiggsFolly