How to Convert to UTC - php

I'm getting dates & times from various sources (e.g. file's date/time from FTP server, email's date/tiem received, etc.) and need to store them all as UTC (so they all have a common reference). How do I do this? What pieces of information do I need in order to properly do the conversion.
This is for a PHP web application. So, I can get my server's time zone. I'm not sure what to do next. Here are some sample inputs:
Mon, 28 Jun 2010 12:39:52 +1200
2010-06-25 15:33:00

For the first case the offset is there so it should be trivial, the second example however will be considered as UTC (or any other default timezone). This is what I suggest:
date_default_timezone_set('UTC'); // set default timezone
$one = strtotime('Mon, 28 Jun 2010 12:39:52 +1200');
$two = strtotime('2010-06-25 15:33:00'); // Already UTC? Must be...
$one and $two will hold the timestamps of the correspondent time converted to the UTC timezone.

You can use strtotime() to convert whatever time format you have into a timestamp and then use whatever function, probably date(), to put it in the format you want everything to be stored in.

Related

How to compare between different date formats?

I have four different date formats that I will store in a DB, Then show the latest ones.
The four different formats:
$a = '27. júní 2018 04:53';
$b = 'Friday, 09 March 2018';
$c = 'Fri, 29 Jun 2018 11:00:00 GMT';
$d = 'Mon, 18 Jun 2018 06:52:20 +0000';
They will be stored in a MYSQL Database.
What should I do with them?
Can SQL or MYSQL date type do the work?
Should I convert them using strtotime()?
Should I extract some data from specific ones to male them match?
MySQL has three data types suitable for date/time values. These are pretty well explained in the documentation.
You have three types of values:
Date alone.
Date with a time, but no time zone.
Date with a time and a time zone.
But the basic questions to ask:
Do you need just the date or is the time also necessary?
Do you need the time zone?
If you need just the date, then date will do. Otherwise, you want datetime or timetamp. Which depends on how you want to treat timezones.
If you actually need to store the timezone with the value, then I would suggest that you think hard about whether this is really necessary. Typically, timestamp is sufficient, because it stores values in UTC which can then be converted to any original timestamp. You can store the original time zone in an alternative column.
If you really need to handle all three types with no compromise, then you might need to use a string. In this case, you should use a correctly formatted string:
YYYY-MM-DD
YYYY-MM-DD HH:MI:SS
YYYY-MM-DD HH:MI:SS+TZ
The first two are readily converted to the appropriate type in MySQL. For the third, you can extract the timezone and add it as an offset (with a bit of work).
However, I doubt whether this approach is necessary. A datetime is probably sufficient.

How to deal with timezones between server and client?

I'm developing a website where I have to deal with different possible timezones from the users. This becomes a great problem since the website hosts time-delicate events like auctions.
All dates/times on the server are in UTC. Database stores everything in UTC timestamps. PHP default timezone is set to UTC too (date_default_timezone_set('UTC');).
Now, my problem is how I should interact with the users, whether I'm only showing a date or, more important, I'm reading a date/time from user input.
A concrete example:
An auction has a deadline, which I store in database as UTC.
When I view the auction on the website, a javascript timer uses a Date object to calculate the remaining time. It automatically converts the timezone to GMT+0100 (my local timezone). So if the deadline is '2013-08-08 10:46:08' (UTC), the javascript date object will return Aug 08 2013 11:26:15 GMT+0100 (GMT Standard Time).
If the current time is greater than 11:46:08 then the timer says that the remaining time is 00:00 (which is correct).
But if I try to insert a bid, the server accepts since the condition on the MySQL INSERT evaluates to true:
INSERT INTO Bids ... WHERE ... AND auction_deadline > NOW() ...
( because auction_deadline = '2013-08-08 10:46:08' and NOW() = '2013-08-08 10:26:50')
All this mumbo jumbo of timezone melts my brains. What am I missing here? I'm almost certain that storing all dates/times in UTC inside the database is the best. I just can't think crystal clear how do deal with it between the user and the database.
Your problem doesn't involve timezones at all, just the fact that clients can turn their clocks or have their clock skewed considerably. For that the fix is to poll the server every once in a while for an offset fix to use in calculations.
In fact, you don't even need date objects. There is a certain universal instant in time when the auction ends. Let's say it is 1375960662823. Right now, the universal instant in time is 1375960669199, so from that we see that the auction ends in 6 seconds (1375960662823 - 1375960669199 ~ 6000 ). It will end in 6 seconds regardless if I am in Morocco or Japan. Do you understand it yet?
To generate these numbers, on the client side you can call var now = Date.now() + skewFix where skewFix is the correction that needs to applied in case client has time skew or manually set their computer to wrong time.
In PHP, you can generate it with $now = time() * 1000;
This is rather a typical subject yet very complex for most to understand. First thing, you never mention the DAYLIGHT SAVING. yeah I am increasing your tension :).
Now let us see how we can do this. You did a good job by saving the Time in UTC. Now, I hope you have registered members and that each member has ability to set their preferred timezone, otherwise you will show Server' timezone based time to them.
When you through "start time" to user you must send them after converting UTC time to their time, similarly when you accept TIME from browser be it user action or javascript you need to convert that time to UTC considering the fact that user is that time zone that he select for his profile.
Hope that clear the idea on where you are going wrong? Please read through day light saving as that will play an important role too when you move ahead with other logic on same.
EDIT:
You can use javascript's Timezone offset, for auto submission and user input based on his settings.
Date in JavaScript uses local timezone. You should get UTC time for the user and send it to the server
new Date
Thu Aug 08 2013 17:00:14 GMT+0530 (India Standard Time)
(new Date("Thu Aug 08 2013 17:00:14")).toUTCString();
"Thu, 08 Aug 2013 11:30:14 GMT"
This will resolve the timezone issue between the server and client.
You said
( because auction_deadline = '2013-08-08 10:46:08' and NOW() = '2013-08-08 10:26:50')
In MySQL - NOW returns the current time in the server's local time zone (docs).
You probably want something like UTC_TIMESTAMP which returns the current time in UTC (docs).
Also - you probably shouldn't accept any input time from the client JavaScript at all. Only trust your own clock. When a bid is placed, use the time on your server in MySQL or in PHP. Don't accept it as input.
You can do the following
once page is loaded, send an ajax request to server with timezone offset of user. You can get timezone offset using the following code.
var curdate = new Date()
var offset = curdate.getTimezoneOffset()
offset is timezone offset in minute.
I think it will help.
everytime when you get the date from the clientside, you can use the getUTC to convert to UTC date ie:
var todayDate = new Date();
var todayDateInUTC = new Date(todayDate.getUTCFullYear(), todayDate.getUTCMonth(), todayDate.getUTCDate(), todayDate.getUTCHours(), todayDate.getUTCMinutes(), todayDate.getUTCSeconds());
so right before you insert the bid date to database, use the getUTC functions to convert it into UTC format.

Get openssl certificate expiration date

I've parsed openssl certificate by openssl_x509_parse() function and got an array as a result.
Now I need to get the expiration time of that certificate. In parsed array I have validTo_time_t element which contains a valid unix timestamp. But how to determine what timezone this timestamp belongs for?
So I can't get the real expiration time because that timestamp because it means deifferent dates on different timezones.
php formats this field using it's default timezone. you can get it using http://docs.php.net/date_default_timezone_get function
and once you know the timezone you can convert it to UTC or whatever you need
Unix TimeStamp have no timezone.
It's defined as number of seconds since January 1st, 1970 at UTC.
It's not a defined as a real date but just a bunch of seconds.
No timezone = no problems.
This is why it's a perfect measure of time across different server and different regions. You can just store unix timestamp, and when you convert it to a date it will use your local timezone to determinate the date, this is completly automatic and this means that when you convert givin a different timezone it will convert to the correct date. Always.
This is true for all timestamp not just for the SSL output.
Major info on Timestamp http://www.unixtimestamp.com/

Changing time zones and getting results from MYSQL based on that

I'm working on a new project which has a lot of different data and it's all stored in database with same time zone timestamp, East coast, I make sure the server time zone is switched to it before anything is loaded via
date_default_timezone_set("America/New_York");
However I can't seem to wrap my head around it, I want to have a search function that allows a time zone selection, what if they select west coast time zone, should I only change the PHP part? Or should I query database differently? All the data is very time sensitive and it's proving very hard to wrap this around my head.
Any help or logic would be appreciated :P
The main problem is that MySQL's support for timezones is laughable. Most other databases let you define the timezone as part of the datetime column, but not MySQL. Instead, they force you to do a connection-wide or server-wide timezone setting.
Your best bet is making sure MySQL stores all datetimes as GMT / UTC. You can enforce this by running SET time_zone = 'UTC' on connect. Do it at the same time as you set the character set. You are setting the connection character set, right?
PHP-side, you can then use a combination of DateTime and DateTimeZone to take the datetimes from MySQL and display them in the user's timezone. For example, let's pretend that we get the date 2012-11-13 14:15:16 from a MySQL DATETIME column. From the PHP interactive prompt:
php > $from_mysql = '2012-11-13 14:15:16';
php > $utc = new DateTimeZone('UTC');
php > $ts = new DateTime($from_mysql, $utc);
php > $pdt = new DateTimeZone('America/Los_Angeles');
php > $ts_pdt = clone $ts;
php > $ts_pdt->setTimezone($pdt);
php > echo $ts_pdt->format('r'), "\n";
Tue, 13 Nov 2012 06:15:16 -0800
As demonstrated, you just need to create the DateTime by expressly telling it you're UTC, if UTC isn't the timezone you've set using date_default_timezone_set. Switching the timezone of a DateTime is as easy as giving it a new one. I've used clone here to work on a copy. DateTimes are mutable, and it's sometimes easy to find yourself accidentally clobbering it.
Reverse date math works the same way, just transform their selection into UTC and run the math on the native numbers.
tl;dr:
Store and perform calculations on datetimes in UTC (GMT) only
Display all datetimes in the user's timezone only

PHP timestamp and displaying correct date and time in different timezones

I'm currently storing dates in my MYSQL database as a PHP timestamp (integer field). However, if I retrieve it from the database and use the PHP date function, would it display the correct time based on the client's time zone.
For example, I display a PHP timestamp 1310674625 (pulled from DB) which is Jul 14 2011 22:17:05 in Eastern Time. So if I display the timestamp in PHP with the code below, would a person viewing the webpage in the Pacific Time Zone see Jul 14 2011 19:17:05 instead?
echo date('M d Y H:i:s', 1310674625);
No. The date will be displayed according to the server's time and timezone, not the user's.
You can offer an option on your site to allow the user provide his/her timezone (or attempt to use geolocation based on the IP) and adjust the output according.
According to this post, reliably determining the user's timezone may not be possible, so for best results, you may need to get input from the user.
EDIT (Based on the request for more information in the comments)
If you need to output the selected timezone, you can use one of the following options:
echo date('e'); // Examples: UTC, GMT, Atlantic/Azores (Available in version 5.1.0 and later
echo date('O'); // Different in Greenwich meantime. Example: +0200
echo date('T'); // Timezone abbreviation. Examples: EST, MDT ...
See the date manual page for more information.
EDIT 2:
To "print the date to a specified timezone" you will need to:
Get the current date as a timestamp (time())
Get the user's timezone offset
Use mktime to add or subtract the user's offset as needed.
Convert the result back to human-readable format using date().
Use date_default_timezone_set if you know users timezone
Also you can use Javascript Date(print timestamp here)

Categories