0

I'm trying to convert a string of numbers I am pulling from a db that looks like this '010219', representing January 2, 2019. I cannot find a way to convert this into 2019-01-02 using php, I just keep getting today's date from the functions I am trying.

Needs to be accomplished with no separators in original string.

  • Please share the functions that you are trying. – ascsoftw Oct 17 '19 at 13:05
  • 5
    Take a look at [`date_create_from_format`](https://www.php.net/manual/en/datetime.createfromformat.php) – Nick Oct 17 '19 at 13:07
  • I've tried a whole slew of different combinations, the problem seems to be with there being no symbols separating the numbers in the string I'm pulling from the db so the functions don't know what to do with it –  Oct 17 '19 at 13:11
  • Not a duplicate because I have no separators in the strings I'm trying to convert –  Oct 17 '19 at 13:12

4 Answers4

2

There are a variety of ways to accomplish this, however the most concise is probably to use date_create_from_format.

An example is here:

$date = date_create_from_format('dmy', '010219');

This will output a Date as so:

echo date_format($date, 'Y-m-d');

Outputs: 2019-02-01

The date_create_from_format function accepts a parameter that defines the format of the date. In this case, the format is dmy which means:

d - Day of month as two-digit number (01-31)
m - Month of year as two-digit number (01-12)
y - Year as two-digit number

The documentation for date_create_from_format is here.

Martin
  • 16,093
  • 1
  • 29
  • 48
2

have you tried something like this?

<?php
$str="010219";

$date = DateTime::createFromFormat('dmy', $str);
echo $date->format('Y-m-d'); //2019-02-01
bomel2k9
  • 141
  • 3
0

$time = strtotime('10/16/2003');

$newformat = date('Y-m-d',$time);

echo $newformat; // 2003-10-16

Please see source: Converting string to Date and DateTime

Two
  • 512
  • 4
  • 17
0

split and concatenate with preg_replace

$newformat = preg_replace("/^(\d\d)(\d\d)(\d\d)$/","20$3-$1-$2","010219");
jspit
  • 7,276
  • 1
  • 9
  • 17