4

I'm using Laravel 5.4 with Jessengers for MongoDB.

I'm using Carbon to manipulate Date/Time.

Problem is my timezone is set (Asia/Dhaka) in config.php but Carbon::now() and mnongoDB's default created and updated fields are in still UTC.

So there is still 6 hrs difference between expected date/time and actually stored date/time .

What I'm missing ? Help will be appreciated

FightForJustice
  • 335
  • 4
  • 16
  • 5
    What you are missing is that the best possible thing to do is actually leave the date stored in UTC. Just because you are in one timezone, does not mean **ALL** potential users are also in that timezone. That's why we use UTC. And why everything defaults to that and makes it so difficult to change it. Because you are meant to leave it that way. – Neil Lunn Jul 16 '17 at 08:52
  • sounds good idea but all users are in same timezone and main problem is ,I'm sending Carbon::now() (current timestamp) but it's saving in utc. What change I have to do if want the data in same timezone ? @NeilLunn – FightForJustice Jul 16 '17 at 09:00
  • Does not matter. When you read the data back and present in in your application, "then" it's formatted as Local Time. But in order to do that correctly in your timezone as well as any other, the source needs to come from UTC. The library and MongoDB are doing the correct thing. Just leave it as it is. And please do not stringify at all costs. – Neil Lunn Jul 16 '17 at 09:02
  • Frankly I really wish this whole issue could be put to bed with a definitive response. Part of the reason why I responded to [Group by Date with Local Time Zone in MongoDB](https://stackoverflow.com/a/45093686/2313887) just recently. Dates belong in UTC. Local timezone presentation is a "client" function. – Neil Lunn Jul 16 '17 at 09:06

1 Answers1

2

Make sure that your timezone setting in config/app.php is correct:

'timezone' => 'Asia/Dhaka',

Then you can compare two values (it should be the same):

$time1 = Carbon::now(config('app.timezone'));
$time2 = Carbon::now();
var_dump($time1->eq($time2);

About MongoDB's default created and updated fields, it depends on your server configuration. You can ask the administrator to change it or don't let it use default time (only set time from Laravel side).

Jared Chu
  • 2,757
  • 4
  • 27
  • 38
  • 1
    Actually my timezone setting was fine! I was confused, cause my DB storing time in different zone ,but this is not an issue because queries executed in my timezone so automatically 6 hours added with mongo results. – FightForJustice Jul 17 '17 at 11:32
  • 1
    So why don't you leave the timezone in Laravel is UTC to make query working right and then display it in your timezone? Timezone in PHP & Database server should be the same. – Jared Chu Jul 17 '17 at 14:30