baig772
baig772

Reputation: 3488

PHP - Convert string to date in

I am getting a string like Wed Sep 28 2016 01:00:00 GMT+0500 (PKT) and I need to convert it to 2016-09-28 01:00:00 I have tried this

$startTime   = strtotime($updatedData['start']);
echo $time = date("Y-m-d H:i:s",$startTime);

but it returns me 2016-09-27 20:00:00

Upvotes: 0

Views: 17109

Answers (4)

Jason Seah
Jason Seah

Reputation: 1564

@copynpaste solution is nice and straight forward but I will still share my solution by using Carbon.

Carbon is a library included together with laravel and here is the documentation.

$carbon = new Carbon('Wed Sep 28 2016 01:00:00 GMT+0500 (PKT)');
$carbon->format('Y-m-d H:i:s');
echo $carbon;

it will come out the result same as DateTime

2016-09-28 01:00:00

So what carbon nice is you can just add day, minute, second and etc by just a very minimal code, here is an example:

$carbon->addDays(1);
echo $carbon;

//result
2016-09-29 01:00:00

Upvotes: 3

danopz
danopz

Reputation: 3408

You could change it to use DateTime:

$startTime = new DateTime('Wed Sep 28 2016 01:00:00 GMT+0500 (PKT)');
echo $startTime->format('Y-m-d H:i:s');

DateTime keeps the timezone you give him.

Live Example: https://3v4l.org/UTltO

Upvotes: 4

Azeez Kallayi
Azeez Kallayi

Reputation: 2642

You can set the desired time zone before converting. Please see the below code as a reference.

date_default_timezone_set("Asia/Bangkok");
$str = 'Wed Sep 28 2016 01:00:00 GMT+0500 (PKT)';
$startTime   = strtotime($str);
echo $time = date("Y-m-d H:i:s",$startTime);

Upvotes: 0

Kinshuk Lahiri
Kinshuk Lahiri

Reputation: 1500

Try this:

$startTime   = strtotime($updatedData['start']);
$time = date("Y-m-d H:i:s",$startTime);
echo date( "Y-M-d H:i:s", strtotime( $time) + 5 * 3600 );

It returns UTC time and you do need to add 5 hours to it. Also a quick suggestion. You can use Carbon for handling the date time.

Upvotes: 0

Related Questions