Friend
Friend

Reputation: 1346

Laravel Setting and Fetching time in UTC

I have set 'timezone' => 'UTC' in app.php ... our database stores datetime in UTC ..We do not have access to database config... so we have to make changes from application end.. Currently its storing value just 2014-09-11 00:00:00 what ever i select from calender..ideally iam trying to fix this

when i insert date from singapore UTC+8 it should store as

'enterdate+8' 2014-09-11 08:00:00 in database.. 

similarly when i insert date from japan utc+9 it should store

'enterdate+9' 2014-09-11 09:00:00 in database

But when a user search 2014-09-11 08:00:00 it should be converted to localtime ...something like 2014-09-11 00:00:00

anyways to fix this in laravel 4 ?

Upvotes: 3

Views: 21824

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81177

Use great Carbon that you have in place:

// for Eloquent
$dateFromDbInLocal = $model->created_at->tz('USER_TIMEZONE');

// for any timestamp
$dateFromDbInLocal = with(new Carbon\Carbon($timestampUTC))->tz('USER_TIMEZONE');

// other way around:
$dateInLocal = new Carbon\Carbon($timestampLocal, 'USER_TIMEZONE');
$dateInUtc = $dateInLocal->tz('utc');

Example:

$now = Carbon\Carbon::now(); // utc 2014-09-10 08:24:50

$japanUser = User::find($someId);
$japanUser->created_at->tz('Japan'); // 2014-09-10 17:24:50

You don't really need to convert anything upon saving, if your app is working in the same timezone as DB. Just do that in the presentation layer, so a user can read the date formatted to his timezone.

Upvotes: 4

Related Questions