Confidence
Confidence

Reputation: 2303

Converting a non standard date string to a mysql datetime string using php

My intention is to convert the following date

20/04/17 13:27:5 to this

20-04-2017 13:27:05

I tried the typical date format functions of php and also Carbon...

things like

$newDate= Carbon::createFromFormat('d/m/y H:m:s', $originalDate);

in this case var_dump($newDate->toDateTimeString()) would bring 2019-03-20 13:00:55 which is not what I expect.

So I was not lucky....is there a way to do this in a straight forward manner?

Upvotes: 0

Views: 111

Answers (4)

BritishWerewolf
BritishWerewolf

Reputation: 3968

I think this should work.

$date = "20/04/17 13:27:5";
$sec  = substr($date, strrpos($date, ":") + 1);
$sec  = substr("0{$sec}", -2);
$new  = substr($date, 0, strrpos($date, ":") + 1) . $sec;

$newDate = Carbon::createFromFormat('d/m/y H:i:s', $new);

I changed the format since you were using m twice for "minutes" and "month". It is correct for the month, but not for the minutes. Instead use i for minutes with leading zeroes.

$sec Is what I used to get the second from the string. This gets the last position of : and will take everything after it. This assumes that you do not change the format of the string.
substr("0{$sec}", -2) Adds a zero to the current second and extracts the last two characters. That means that 50 becomes 050 and then the last two characters are 50 so we end up without the padding, but 5 becomes 05 and the last two characters are the only characters.

$new concatenates the start of the date string and the new second with the zero padding.

$newDate is your original string with the format changed.

Upvotes: 2

B. Desai
B. Desai

Reputation: 16436

There is issue with seconds. There must be 05 not only 5

<?php

    $original_date = "20/04/17 13:27:5";
    $date_explode = explode(":", $original_date);
    $date_explode[2] = str_pad($date_explode[2],2,"0",STR_PAD_LEFT);
    $original_date = implode($date_explode,":");

    $date = DateTime::createFromFormat('d/m/y H:i:s', $original_date);
    echo date_format($date,"d-m-Y H:i:s");

?>

Upvotes: 1

C. Norris
C. Norris

Reputation: 600

Isn't it like this?

$newDate = Carbon::createFromFormat('d/m/y H:i:s', $originalDate);

Upvotes: 0

arkascha
arkascha

Reputation: 42925

This is a working conversion routine that creates the ISO format you are looking for. But as already mentioned you need to "fix" the strange way the seconds are specified in the original example you provide. You will have to use string functions if that really is the format you receive. Better would be to fix the code that creates such broken formats.

<?php
$input = '20/04/17 13:27:05';
$date = DateTime::createFromFormat('d/m/y H:i:s', $input);
var_dump($date->format('d-m-Y H:i:s'));

The output obviously is:

string(19) "20-04-2017 13:27:05"

Upvotes: 0

Related Questions