Search code examples
phpdatetimeutc

IST to UTC timestamp in php


I have a date time like 30-10-2018 06:00:00 pm, Now I want to convert it into UTC timestamp, so I am trying to convert this to strtotime and multiplying it by 1000. But it leading to 6hrs difference in the resulted date

$min_date = "30-10-2018 06:00:00 pm";
$max_date= "30-10-2018 07:00:00 pm";

echo $minDate= strtotime($min_date) * 1000; 
echo "<br>";
echo $maxDate= strtotime($max_date) * 1000;

Solution

  • What you want to use is a built-in PHP function known as "gmdate."

    Let's use your first timestamp, $min_date, in our example of using gmdate to convert the datetime string to a UTC timestamp:

    $min_date = "30-10-2018 06:00:00 pm";
    
    //Use 'gmdate', which accepts a formatting string and time() values as arguments.
    $utc_min_date = gmdate("d-m-Y H:i:s", strtotime($min_date));
    
    echo "<p>Before: ".$min_date."</p>"; 
    //Produces: "Before: 30-10-2018 06:00:00 pm"
    
    echo "<p>UTC: ".$utc_min_date."</p>"; 
    //Produces: "UTC: 30-10-2018 23:00:00"
    

    If you're wanting a purely numerical representation, akin to a time() stamp, you can simply convert the resulting UTC timestamp.

    $numerical_utc_min_date = strtotime($utc_min_date);
    
    echo "<p>Numerical UTC timestamp: " . $numerical_utc_min_date . "</p>";
    //Produces: "Numerical UTC timestamp: 1540958400"