Search code examples
phpunixtimeutctimezone-offset

TimeZone for unix, UTC time to Human readable time conversion


I am fetching Weather information from this API using PHP. My output is like below

enter image description here

I need to convert sunrise and sunset value to human readable format using PHP. In this regard I need to use TimeZone like Asia/Kolkata.

How can I get TimeZone to get sunrise and sunset value to human readable format ?


Solution

  • The DateTime class is used to create an object from the timestamp 1638318242. If a DateTime object is created from a timestamp, the time zone is always UTC. With the method setTimeZone() the object is converted into the desired time zone (here Asia/Kolkata). The output can then be brought into the desired form using the format method.

    <?php
    $sunrise = 1638318242;
    
    $dateTime = date_create('@'.$sunrise)->setTimeZone(new DateTimeZone("Asia/Kolkata"));
    
    echo "Sunrise in Calcutta on ". $dateTime->format('F j, Y \a\t H:i');
    //Sunrise in Calcutta on December 1, 2021 at 05:54