简体   繁体   中英

DateTime (Timezones) in PHP Web Applications

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 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM