How to format date in PHP from string of concatenated numbers?

I am new to PHP and I am trying to learn more about php date and time, but I seem to be stuck with this.

I have this date format:

ddMMyyHHmmss 

And the example is 120813125055, but I'm trying to manipulate a string so that it gives me the format:

  yyyy-MM-dd HH:mm:ss (in the example above, 2013-08-12 12:50:55) 

I tried to do something like:

  date('Ymd H:i:s', strtotime('120813125055')); 

But it always gives me the result 1969-12-31 18:00:00.

I suppose I need to do some string manipulation in PHP for this, but I was wondering if there is a simpler and more efficient way to do this?

+4
source share
4 answers

I think what you are looking for is in the second answer here: how to reformat the datetime string in php?

To summarize (and apply to your example), you can change the code as follows.

 $datetime = "120813125055"; $d = DateTime::createFromFormat("dmyHis", $datetime); echo $d->format("Ymd H:i:s"); 
+4
source

Use date_create_from_format :

 $ts = date_create_from_format('dmyHis', '120813125055'); $str = date('Ymd H:i:s', $ts); 

strtotime () only works with easily recognizable formats. This is an ugly combination of garbage, so it is not surprising that strtotime is freed from boolean FALSE for failure, which then gets cast to int 0 when trying to return it back to date() .

And of course, note that your time string is NOT y2k compatible. double-digit years should never be used again, except for demonstration purposes.

+4
source

You are using your function call, and the argument is in the wrong way.

In your example, php will try to return a date for which the time is specified as 'strtotime (' 120813125055 ')', and this function returns false (interpreted as 0). Thus, you return a date formatted in "Ymd H: i: s" for the Unix era.

You will need to get the actual timestamp of your string, so use http://www.php.net/manual/en/datetime.createfromformat.php .

0
source

You are mistaken here.

 I tried to do something like: date('Ymd H:i:s', strtotime('120813125055')); 

You should not use only numbers (it does not matter if it is an integer or a string) than it will always give you the same.

You can use any other valid date and time (EG June 6, 2013, May 5, 12 ...). Because what strtotime () does is determine the actual date and convert it to a timestamp.

0
source

Source: https://habr.com/ru/post/1496625/


All Articles