0

I want to convert a text string to a datetime and then output in a different format. I think i can do this with date_create_from_format(), but this doesn't return any detail.

$datetime=date_create_from_format( 'Y-m-d.H:i:sP'  , '2020-05-26T11:03:00+00:00' );
$newdatestring=date('g:iA', $datetime);
1
  • 1
    You may want to look at strtotime() Commented May 27, 2020 at 13:50

2 Answers 2

2

You may try with the following simple code. Note, that if you want to include a literal character in the format, you need to escape it with a backslash (\). The result from date_create_from_format() / DateTime::createFromFormat() call is a DateTime object representing the date and time specified by the time string, so you need to format it appropriately.

Procedural:

<?php
$datetime = date_create_from_format('Y-m-d\TH:i:sP', '2020-05-26T11:03:00+03:00');
echo date_format($datetime, 'g:iA');
?>

Object-oriented:

<?php
$datetime = DateTime::createFromFormat('Y-m-d\TH:i:sP', '2020-05-26T11:03:00+03:00');
echo $datetime->format('g:iA');
?>

Output:

11:03AM
Sign up to request clarification or add additional context in comments.

Comments

2

Keep it simple with the DateTime class:

$datetime = new DateTime('2020-05-26T11:03:00+00:00');

$newdatestring = $datetime->format('g:iA');

If necessary, you can also use DateTime::createFromFormat

1 Comment

The code you posted ($datetime = new DateTime('2020-05-26T11:03:00+00:00'); $newdatestring = $dt->format('g:iA');) returns errors (Undefined variable: dt ... and Uncaught Error: Call to a member function format() on null ...).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.