Indian Date and Time in php

Guys I am trying to get correct Indian time and date in PHP

I tried this code:

$date = date("d/m/Y");
$date1 =  date("H:i a");

if(function_exists('date_default_timezone_set'))
{
    date_default_timezone_set("Asia/Kolkata");
}

echo $date;
echo $date1;

      

But I am not getting the correct time. I get the time that 4.30

Time is late. Is there a bug in my code?

+3


source to share


3 answers


Place your timezone declaration first before using any date function:



// set the timezone first
if(function_exists('date_default_timezone_set')) {
    date_default_timezone_set("Asia/Kolkata");
}

// then use the date functions, not the other way around
$date = date("d/m/Y");
$date1 =  date("H:i a");

echo $date . '<br/>';
echo $date1;

      

+4


source


Cleaning option -

$date = new DateTime(null, new DateTimezone("Asia/Kolkata"));
echo $date->format('d/m/y').'<br/>';
echo $date->format('H:i a');

      



This way you won't change the global state, so other code snippets might use different time zones

+2


source


<?php
date_default_timezone_set("Asia/Kolkata");
echo "The date is " .date("d/m/y"); 
echo "<br/>";
echo "The time is " . date("h:i:sa");
?>

      

0


source







All Articles