我有一个原始日期时间,然后我使用子字符串来抓取每个字符以形成日期时间。现在我想将它转换为正确的日期时间,这样如果我在几小时内添加8小时,它将永远不会显示25的输出,而是显示1。
这是我用于连接原始数据的代码
RAW DATA
$datetime = "150205172701";
我的代码在日期之后制作数据
$hour = substr($datetime, 6, 2) + 8;
$minutes = substr($datetime, 8, 2);
$second = substr($datetime, 10, 2);
$year = substr($datetime, 0, 2);
$month = substr($datetime, 2, 2);
$day = substr($datetime, 4, 2);
$findate = "20" .$year. "-" .$month. "-" .$day. " " .$hour. ":" .$minutes. ":" .$second. ".000";
结果将是 2015-02-05 25:27:01.000
预期结果 2015-02-05 01:27:01.000
答案 0 :(得分:0)
$datetime = "150205172701";
$php_timestamp_date = date("Y-m-d H:i:s", $datetime);
echo $php_timestamp_date;
试试这个
答案 1 :(得分:0)
尝试date_create_from_format方法:
$findate = date_create_from_format ( "Y-m-d G:i:s" , "20" .$year. "-" .$month. "-" .$day. " " .$hour. ":" .$minutes. ":" .$second. ".000");
格式String指定dateTime
的所需输出格式 Y - 4位数年份
m - 带有前导零的数字的月份
d - 带有前导零的数字日
G - 带有前导零的24小时时间
我 - 领先的零分钟
s - 带有前导零的秒数
如果要更改格式,请选中http://php.net/manual/en/datetime.createfromformat.php
答案 2 :(得分:0)
使用以下代码
<?php
$datetime = 150205172701;
$minutes = substr($datetime, 8, 2);
$second = substr($datetime, 10, 2);
$year = substr($datetime, 0, 2);
$month = substr($datetime, 2, 2);
$day = substr($datetime, 4, 2);
$findate = "20" .$year. "-" .$month. "-" .$day. " " .$hour. ":" .$minutes. ":" .$second. ".000";
echo $findate; //2015-02-05 01:27:01.000
?>
希望这有助于你
答案 3 :(得分:0)
我认为你正在寻找这个,拿走你建立的日期字符串并添加一定的时间。
<?php
$datetime = "150205172701";
$hour = substr($datetime, 6, 2);
$minutes = substr($datetime, 8, 2);
$second = substr($datetime, 10, 2);
$year = substr($datetime, 0, 2);
$month = substr($datetime, 2, 2);
$day = substr($datetime, 4, 2);
$findate = "20" .$year. "-" .$month. "-" .$day. " " .$hour. ":" .$minutes. ":" .$second. ".000";
$date = new DateTime($findate);
$date->add(new DateInterval('PT08H')); //this is where you will add the amount of time
echo $date->format("Y-m-d G:i:s");
?>
这将输出:
2015-02-06 1:27:01
答案 4 :(得分:0)
您必须将
hour
除以24,并且将1
给出不在前的零。所以,我为($hour<10)
设置了条件,然后追加零。
$datetime = "150205172701";
$hour = floor((substr($datetime, 6, 2) + 8)/24);
$hour = ($hour<10)?"0".$hour : $hour;
//Your code as it is
$minutes = substr($datetime, 8, 2);
$second = substr($datetime, 10, 2);
$year = substr($datetime, 0, 2);
$month = substr($datetime, 2, 2);
$day = substr($datetime, 4, 2);
echo $findate = "20" .$year. "-" .$month. "-" .$day. " " .$hour. ":" .$minutes. ":" .$second. ".000";
<强> Demo 强>
答案 5 :(得分:0)
你这太复杂了。看看\DateTime classes,你会发现它可以简单到: -
$datetime = "150205172701";
$date = \DateTime::createFromFormat('ymdHis', $datetime);
echo $date->format('Y-m-d H:i:s.u');
输出: -
2015-02-05 17:27:01.000000