how to re-format datetime string in php?

2019-01-07 20:38发布

I receive a datetime from a plugin. I put it into a variable:

$datetime = "20130409163705"; 

That actually translates to yyyymmddHHmmss.

I would need to display this to the user as a transaction time but it doesn't look proper.

I would like to arrange it to be like 09/04/2013 16:37:05 or 09-apr-2013 16:37:05.

How do I go about and change the orders of the string?

As for now I could think is to use substr to separate the date and time. I'm still not sure on how to add the additional characters and rearrange the date.

7条回答
狗以群分
2楼-- · 2019-01-07 20:53

If you want to use substr(), you can easily add the dashes or slashes like this..

$datetime = "20130409163705"; 
$yyyy = substr($datetime,0,4);
$mm = substr($datetime,4,6);
$dd = substr($datetime,6,8);
$hh = substr($datetime,8,10);
$MM = substr($datetime,10,12);
$ss = substr($datetime,12,14);
$dt_formatted = $mm."/".$dd."/".$yyyy." ".$hh.":".$MM.":".$ss;

You can figure out any further formatting from that point.

查看更多
\"骚年 ilove
3楼-- · 2019-01-07 20:53
https://en.functions-online.com/date.html?command={"format":"l jS \\of F Y h:i:s A"}
查看更多
该账号已被封号
4楼-- · 2019-01-07 20:54

For PHP 5 >= 5.3.0 http://www.php.net/manual/en/datetime.createfromformat.php

$datetime = "20130409163705"; 
$d = DateTime::createFromFormat("YmdHis", $datetime);
echo $d->format("d/m/Y H:i:s"); // or any you want

Result:

09/04/2013 16:37:05
查看更多
放荡不羁爱自由
5楼-- · 2019-01-07 20:59

why not use date() just like below,try this

$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);

and will be output

09/04/13 16:37:05
查看更多
beautiful°
6楼-- · 2019-01-07 21:02

You could do it like this:

<?php
$datetime = "20130409163705"; 
$format = "YmdHis";

$date = date_parse_from_format ($format, $datetime);
print_r ($date);
?>

You can look at date_parse_from_format() and the accepted format values.

查看更多
Summer. ? 凉城
7楼-- · 2019-01-07 21:14

try this

$datetime = "20130409163705"; 
print_r(date_parse_from_format("Y-m-d H-i-s", $datetime));

the output:

[year] => 2013
[month] => 4
[day] => 9
[hour] => 16
[minute] => 37
[second] => 5
查看更多
登录 后发表回答