0

I want to insert current date and time in mysql using php. I dont want to set timezone in my init.php as this is not my requirement to force the user to set timezone everytime or once.

I am doing it:

echo "Today is " . date("d/m/Y") . "<br>";
echo "Time is " . date("g:m a") . "<br>";
$sys_timestamp = strtotime(exec("date"));
echo sys_timestamp;

I have tried NOW(), but it is also not solving my problem. I have tried systime(), time() as well.

I was trying to fix like below but it messed up all the timings.

 date_default_timezone_set('Europe/Helsinki');
 $updated_date = date("d-m-Y");
 echo $updated_date;

 $updated_time = date("g:i a");
 echo $updated_time;

Not I dont want above solutions. I want to send common date and time on server for the whole website and I want when the user check the date & time, the date & time automatically convert it to their local time using php. Convert time from mysql inserted time to the user's location local time and date.

Kindly suggest what I am doing wrong.

Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
Sarah
  • 405
  • 2
  • 7
  • 23

2 Answers2

0

This will sync the timezone offest of the SQL session to w\e timezone php is currently set to. Otherwise your php session and sql sessions are running on different times zones if you just change the php.

date_default_timezone_set('Europe/Helsinki');

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$now = new DateTime();
$mins = $now->getOffset() / 60;
$sgn = ($mins < 0 ? -1 : 1);
$mins = abs($mins);
$hrs = floor($mins / 60);
$mins -= $hrs * 60;
$offset = sprintf('%+d:%02d', $hrs*$sgn, $mins);

$sql = "SET time_zone='".$offset."';"; 
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->close();
Mason Stedman
  • 613
  • 5
  • 12
0

Change your column
see this Sceenshot


When You insert Data into table, Column automatically fill current date & time also.