Indian Date and time in php
Asked Answered
S

7

5

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?

Sanguineous answered 31/10, 2014 at 8:23 Comment(0)
S
8

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;
Stitching answered 31/10, 2014 at 8:25 Comment(0)
C
3

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

Cremona answered 31/10, 2014 at 9:15 Comment(1)
Best answer :).Perlaperle
J
1
<?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");
?>
Juryman answered 30/3, 2018 at 16:53 Comment(1)
Please provide an explanation alongside your code. Code only answers are frowned upon in the community guidelines.Rearm
B
0

I think you should try this

date_default_timezone_set('Asia/Kolkata');
and $date = date('Y-m-d H:i:s'); what ever format you like!!

Bedraggle answered 1/6, 2018 at 10:38 Comment(0)
H
0
// 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;
Hyson answered 27/8, 2018 at 10:26 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Durga
B
0

Get Indian time and date now

<?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");
?>
Bouillabaisse answered 5/5, 2023 at 11:6 Comment(1)
Hi, your answer replicates some others. While answering, be sure to add some value and not just repurposing existing content. Please read how to answerStandstill
M
0

you should try

date_default_timezone_set('Asia/Kolkata');

$date = date('Y-m-d h:i:s');

echo "Current Data & time-->".$date;

Malvoisie answered 2/2 at 7:12 Comment(1)
How does your answer differ from previous ones?Sorites

© 2022 - 2024 — McMap. All rights reserved.