0

I get a date value from the port. And I want to convert that string value to datetime. But I couldn't figure out how. Deletes 0 at the beginning of the code the way I tried.

Incoming value:

;03122019;164202;

My code:

$data = fread($socket, 1024);
$down= array();
$down= split("#",$data);
$list_n= split(";",$down[$i]);
$time = '';
$time = strval($list_n[1])+''.$list_n[2];
$newformat = date('Y-m-d H:i:s',$time);
echo "Time ---------------> ".$time;
echo $newformat;

Result:

Time ---------------> 3122019164202
 3122-01-19 23:01:57

Deleting the initial 0. I want to edit these values and insert them into the database.

I want:

Time ---------------> 2019-12-03 16:42:02
Tota1907
  • 23
  • 2
  • 7
  • 1
    i think you need to echo the $newformat not the $time – rrsantos Dec 04 '19 at 00:52
  • I tried it. But result : '3122-01-19 23:01:57' @rrsantos – Tota1907 Dec 04 '19 at 00:57
  • Does this answer your question? [Convert uncommon date format to timestamp in most efficient manner possible?](https://stackoverflow.com/questions/4843423/convert-uncommon-date-format-to-timestamp-in-most-efficient-manner-possible) – henriquehbr Dec 04 '19 at 01:50

1 Answers1

0

You can use DateTime::createFromFormat

$dateTime = str_replace(";","",";03122019;164202;");
$date = DateTime::createFromFormat('dmYHis', $dateTime);
echo $date->format('Y-m-d H:i:s');

Update: thank for @Nemoden's suggest, you can use createFromFormat without the str_replace()

$dateTime = ";03122019;164202;";
$date = DateTime::createFromFormat(';dmY;His;', $dateTime);
echo $date->format('Y-m-d H:i:s');

Output:

2019-12-03 16:42:02
catcon
  • 1,295
  • 1
  • 9
  • 18
  • 1
    beat me to this... :) but my improvement over the code is that you can actually leave those `;` in the format, so there is not need to `str_replace` anything – Nemoden Dec 04 '19 at 01:08
  • Deleted my answer. The only difference is absence of `str_replace`, but the format of `DateTime::createFromFormat` is `';dmY;His;` – Nemoden Dec 04 '19 at 01:14
  • if you could illustrate that, that'd be great :) – Nemoden Dec 04 '19 at 01:14