Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indian Date and time in php

Tags:

date

php

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

I have 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 correct time. I am getting time which is 4.30 Hours late. Is there any mistake in my code?

like image 444
MukulAgr Avatar asked Oct 31 '14 08:10

MukulAgr


2 Answers

Put the 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;
like image 153
Kevin Avatar answered Oct 11 '22 18:10

Kevin


The cleaner option is

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

This way, you wouldn't alter global state, so other pieces of the code can still use other timezones

like image 31
JimiDini Avatar answered Oct 11 '22 17:10

JimiDini