php: setting a timezone by UTC offset

2019-01-06 14:35发布

Using javascript I know that my users timezone is UTC +3.

Now I want to create DateTime object with this knowledge:

$usersNow = new DateTime('now', new DateTimeZone("+3"));

I receive as a respsonse:

'Unknown or bad timezone (+2)'

What am I doing wrong? How can I fix?

10条回答
萌系小妹纸
2楼-- · 2019-01-06 15:15

DateTimeZone requires a timezone not an offest

查看更多
别忘想泡老子
3楼-- · 2019-01-06 15:16

Modern answer:

$usersNow = new DateTime('now', new DateTimeZone('+0300'));

Documentation:

http://php.net/manual/en/datetimezone.construct.php

查看更多
Bombasti
4楼-- · 2019-01-06 15:21

For anyone who comes across this, I was facing the same problem, so in the end I extended the DateTime class and overrode the __construct() method to accept an offset (in minutes) instead of a timezone.

From there, my custom __construct() works out what the offset is in hours and minutes (e.g. -660 = +11:00) and then uses parent::__construct() to hand my date, custom formatted to include my offset, back to the original DateTime.

Because I'm always dealing with UTC times in my application, my class also modifies the UTC time by subtracting the offset, so passing Midnight UTC and an offset of -660 will show me 11am

My solution is detailed here: https://stackoverflow.com/a/35916440/2301484

查看更多
成全新的幸福
5楼-- · 2019-01-06 15:24

did you try this

http://php.net/manual/en/function.strtotime.php

 <?php
    echo strtotime("now"), "\n";
    echo strtotime("10 September 2000"), "\n";
     echo strtotime("+5 hours");
    echo strtotime("+1 day"), "\n";
    echo strtotime("+1 week"), "\n";
    echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
    echo strtotime("next Thursday"), "\n";
    echo strtotime("last Monday"), "\n";
    ?>
查看更多
登录 后发表回答