-1

I have a string like this "20180720171534449" which is a kind of time stamp, is there an easy way I can convert this using PHP and format it as a date or date and time that makes sense to a human?

TIA

Peter

Peter
  • 1
  • 5

1 Answers1

1

You have an 'YmdHisv' format where v is miliseconds.
Miliseconds is not parsable (as I found out today) with date_create_from_format so you need to remove that first from the string with substr.

$s = "20180720171534449";
$date = date_create_from_format('YmdHis', substr($s,0,-3));
echo date_format($date, 'Y-m-d H:i:s'); //2018-07-20 17:15:34

https://3v4l.org/m1XNd


As Ghost pointed out milliseconds is parasble if using microseconds u instead.

$s = "20180720171534449";
$date = date_create_from_format('YmdHisu', $s);
echo date_format($date, 'Y-m-d H:i:s\.v'); //2018-07-20 17:15:34.449
Andreas
  • 23,610
  • 6
  • 30
  • 62
  • 2
    no need to make string operations, since microseconds can take 2 up to 6 digits https://3v4l.org/VW8sh – Kevin Jul 23 '18 at 07:09
  • Didn't know about the `u` I thought it was `v`. Thanks! – Andreas Jul 23 '18 at 07:13
  • Thankyou, that worked great! :-) – Peter Jul 23 '18 at 07:16
  • 1
    @Peter No problem. I see that you are new here, take the tour and learn some of the basics of SO https://stackoverflow.com/tour and you will ern a badge when you have read the full page. – Andreas Jul 23 '18 at 07:24