Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reformat a date in PHP

Tags:

php

I have a date/time string like this: 180510_112440 in this format ddmmyy_hhmmss I need a snippet for having a string formatted like this way: 2010-05-18 11:24:40 Thanks for help.

like image 977
Kreker Avatar asked Oct 14 '22 05:10

Kreker


2 Answers

another possible answer is the common use of strptime to parse your date and the mktime function:

<?php

$orig_date = "180510_112440";

// Parse our date in order to retrieve in an array date's day, month, etc.
$parsed_date = strptime($orig_date, "%d%m%y_%H%M%S");

// Make a unix timestamp of this parsed date:
$nice_date = mktime($parsed_date['tm_hour'],
                    $parsed_date['tm_min'],
                    $parsed_date['tm_sec'],
                    $parsed_date['tm_mon'] + 1,
                    $parsed_date['tm_mday'],
                    $parsed_date['tm_year'] + 1900);

// Verify the conversion:
echo $orig_date . "\n";
echo date('d/m/y H:i:s', $nice_date);
like image 102
Patrick Avatar answered Oct 26 '22 23:10

Patrick


$inDate = '180510_112440';
$date = strtotime('20'.substr($inDate,4,2).'-'.
        substr($inDate,2,2).'-'.
        substr($inDate,0,2).' '.
        substr($inDate,7,2).':'.
        substr($inDate,9,2).':'.
        substr($inDate,11,2));

echo date('d-M-Y H:i:s',$date);

Assumes date will always be in exactly the same format, and always 21st century

like image 25
Mark Baker Avatar answered Oct 27 '22 00:10

Mark Baker