Link to home
Start Free TrialLog in
Avatar of Eric Calkins
Eric CalkinsFlag for United States of America

asked on

Convert from UTC to local time based on lat/long?

Alrighty, I've done a ton of googling but I need some thoughts/ideas.  I'm pulling records out of my database, these records do include a latitude column, longitude column, and a datetime column.  I need to somehow convert that datetime string, that's in UTC, to the local time based on the lat/long.  The idea would to add another column such as Local Time to this email.  I've included the code I'm using as a reference.  The code does work (I just double checked it).  I have a lot to learn and I'm not an expert so please excuse my code hacking.

Thank you in advance!
Eric :)

<?php

$conn=mysqli_connect("localhost","REMOVED","REMOVED","REMOVED");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$sql = "SELECT config.nodeid, config.loc_city, config.loc_state, config.latitude, config.longitude, event_data.compass, event_data.heading, event_data.pressure, event_data.datetime, event_data.event_type FROM config INNER JOIN event_data ON config.nodeid = event_data.nodeid AND event_data.event_type = 'alertStart' AND event_data.datetime > DATE_SUB(NOW(), INTERVAL 1 DAY) ORDER BY `config`.`nodeid` ASC;";

$result = mysqli_query($conn, $sql);
$num_rows = mysqli_num_rows($result);

    $header ="From: example@example.com" . "\r\n";
    $email    = 'example@example.com';
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    $subject  = 'ALERT: ' . $num_rows . ' Nodes Reported alertStart!';
    $message = 'The following nodes reported an alertStart in the last 24 hours:
    <table border="1">
        <tr>
            <td>Node</td>
            <td>City</td>
            <td>State</td>
            <td>Compass</td>
            <td>Heading</td>
            <td>Pressure (in/Hg)</td>
            <td>Alert Time - UTC</td>
        </tr>
        ';
while ($row = mysqli_fetch_array($result)){
$message .="<tr>";
$message .="<td>".$row['nodeid']."</td>";
$message .="<td>".$row['loc_city']."</td>";
$message .="<td>".$row['loc_state']."</td>";
$message .="<td>".$row['compass']."</td>";
$message .="<td>".$row['heading']."</td>";
$message .="<td>".$row['pressure']."</td>";
$message .="<td>".$row['datetime']."</td>";
$message .="</tr>";
}
$message .="</table>EOF";

	mail($email, $subject, $message, $header);

?>

Open in new window

Avatar of Dr. Klahn
Dr. Klahn

This is not at all an easy task.

Time zones are gerrymandered, and some of them are off by strange values such as half an hour.  In one area in Arizona there is the Arizona time zone, and a different time zone inside that in a reservation, and another different time zone inside that inside a different reservation.

Trying to build and maintain a local time zone boundary database is futile.  Time zone boundaries change constantly and any database that is correct this week won't be correct next month.  Probably the easiest thing to do is call out to one of the web sites that can do a conversion.  Have a look at the article at that other site:

https://stackoverflow.com/questions/16086962/how-to-get-a-time-zone-from-a-location-using-latitude-and-longitude-coordinates
Avatar of Eric Calkins

ASKER

Thank you for the info, I did see that link you sent during my research.  I was hoping I could use Google Time Zone API to get this done, and was also hoping it was simple enough that I could get help on here but it sounds like that might not be an option based on the complexity though.

I'm thinking that, when I enter users in to my database that I could enter the UTC offset at that time (I manually enter lat/long too).  This way I could just use that column to calculate the local time.  Th only issue with that plan is dealing with DST.

I'm going to leave this question open for a little while longer, just to get a little more input/ideas - I do realize I may need to look outside EE for help with writing the code though.

Thanks!
Eric
Ok Latitude is not involved.   Longtitude is. Divide the longtitude by 15. Every 15 degrees   is another timezone based on longtitude.
If you need to find the timezone there are GMT-1, GMT-2, ...GMT-12 and  GMT +1, ... GMT +12... Those can be used to select from the longtitude.

To find the right "timezone" like CET, CEST, EST, etc. etc. is quite a different tack. As the timezones are political driven items.   and only have a slight resemblance to reality.
Say france is on CET ==> Currently Summertime so +2Hours .... That is the same as Greece/Eastern Europe,Ukraine sun time.
That is a hard thing to map, as those don't exactly follow the longtitudes. Also be aware that in the pacific there is some places where the dateline has a few bulges to keep some countries on the same date.
(in 2018 timezone data was changed 9 times, this year it changed 2 times)
Using https://developers.google.com/maps/documentation/timezone/start provides correct timezone calculations based on many factors, the gerrymandering Dr. Klahn mentioned.

Specifically, some lat/long... how to say this... notches can overlap into previous or next timezone base on the randomness of local politics at the time the notch was created, which might be decades long past.

Best to just use the Google Timezone API to keep things simple.
Tip: If you're making... massive numbers of API calls, write a caching system so you only call Google's API once, then cache the results locally, as timezones rarely change.

I'd also setup a Google Alert tracking "timezone change", so you get an email anytime some random timezone changes, then you can just manually drop all the data for that timezone from your local caching system.

I mention this, as some... crazier than usual U.S. politicians... are talking about changing some US timezones right now.
Not only in the US, also the EU is transitioning to an area where there will be no Summertime.   [ no changes in spring &  autumn  anymore ].
So there will be more differences coming up.

side note:
Ridiculous example  wrt. to politics surrounding this:
Some politicians tend to opt to  stay in "summer time" because it associates with warmth, happy times etc.  even though it will cause the time to be off by 2 hours for solar-local time for more than half of Europe.  This might actually cause some increase in deaths & depressions due to this imbalance.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.