开发者

DateTime (Timezones) in PHP Web Applications

开发者 https://www.devze.com 2023-02-06 03:53 出处:网络
I learnt that I should Store UTC and Show in local time. How can I query the SQL database for rows that are due today, according to user time. I have a Todo table with a column dueOn it contains the U

I learnt that I should Store UTC and Show in local time. How can I query the SQL database for rows that are due today, according to user time. I have a Todo table with a column dueOn it contains the UTC Unix Timestamp in int.

I think it will look something like

SELECT * FROM Todos 
WHERE dueOn BETWEEN {today's timestamp} AND {tomorrow's timestamp}

What will I use开发者_JS百科 to get today's & tomorrow's timestamp? I think this sounds simple, but I am very confused with all the similar methods for date & time

UPDATE

I am wondering of something like below is correct

// set default timezone to the user's timezone
date_default_timezone_set("Asia/Singapore"); 
// get UTC datetime for today & tomorrow
$today = DateTime::createFromFormat('Y-m-d', date('Y-m-d'), new DateTimeZone('UTC')); 
$tomorrow =  clone($today);
$tomorrow->add(DateInterval::createFromDateString('1 day'));

$sql = 'SELECT * FROM Todos WHERE dueOn BETWEEN ' . $today->getTimestamp() . ' AND ' . $tomorrow->getTimestamp();
echo $sql;

Can I somehow get the user's time without using date_default_timezone_set? Or will it be allright as that will just set the timezone for the request?


In your SQL query, use CONVERT_TZ to convert the due date from the user's time to UTC.

Ex:

SELECT * FROM Todos
WHERE CONVERT_TZ('2011-01-21', 'EST', 'UTC') BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 1 DAY)
0

精彩评论

暂无评论...
验证码 换一张
取 消