Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

createFromTimestamp does not respect the default timezone #2966

Closed
arokettu opened this issue Mar 13, 2024 · 4 comments
Closed

createFromTimestamp does not respect the default timezone #2966

arokettu opened this issue Mar 13, 2024 · 4 comments
Labels
expected behavior The actual behavior is expected

Comments

@arokettu
Copy link

Hello,

I encountered an issue with the following code:

<?php

require __DIR__ . '/../vendor/autoload.php';

date_default_timezone_set('America/New_York');
$d = \Carbon\CarbonImmutable::createFromTimestamp(1710358665);
var_dump($d->format('c'));

Carbon version: 3.1.1

PHP version: 8.3.4

I expected to get:

string(25) "2024-03-13T15:37:45-04:00"

But I actually get:

string(25) "2024-03-13T19:37:45+00:00"

Thanks!

@arokettu
Copy link
Author

All >= 3.0.0 are affected

@kylekatarnls
Copy link
Collaborator

Hello,

This is an expected breaking change. As timestamp is by nature UTC (it's the number of seconds since January 1st 1970 00:00 UTC), that's the reason why DateTime itself won't convert your object into New_York timezone if you do this with pure PHP:

date_default_timezone_set('America/New_York');
$d = new DateTime('@1710358665');
var_dump($d->format('c'));

Carbon 2 was incorrectly using date_default_timezone_get() and Carbon 3 is now aligning its behavior with DateTime parent class.

But you can still use it explicitly:
CarbonImmutable::createFromTimestamp(1710358665, date_default_timezone_get())

As a second note, I strongly recommend you always set default timezone to UTC and work with user/context timezone locally instead of globally.

@kylekatarnls kylekatarnls added the expected behavior The actual behavior is expected label Mar 13, 2024
@arokettu
Copy link
Author

Then PHPdoc should be fixed too at least:

Create a Carbon instance from a timestamp and set the timezone (use default one if not specified).

and I would expect it to be documented somewhere as a breaking change

and what's the purpose of createFromTimestampUTC now?

@kylekatarnls
Copy link
Collaborator

createFromTimestampUTC is indeed strictly equivalent to createFromTimestamp without timezone parameter. If you pass a timezone as a second parameter, only createFromTimestamp can do, if you want UTC, then you can call createFromTimestampUTC for explictness.

I will change the documentation. This is indeed incorrect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
expected behavior The actual behavior is expected
Projects
None yet
Development

No branches or pull requests

2 participants