ctabuyo ctabuyo - 4 years ago 136
C# Question

Get local time based on coordinates

I am programming an application that should give the local time based on the coordinates (lat&long) that you give it.

I only know of 2 methods to do that:

1st: Get the TimeZone Name, and then find its local time.
2nd: Use the Google API and receive the time as an offset and UTC not Local.

I decided to use the 1st method because seemed easier, so I decided to use the GeoTimeZone to get the Time Zone... Problem is that then I don´t know how to get the local time on that TimeZone... Here´s the code I wrote to get the TimeZone name.

string tz = TimeZoneLookup.GetTimeZone(lat, lon).Result;


variables
lat
&
lon
are of course the coordinates.

Thank you!

Edit: My question is how can I get the LocalTime on that TimeZone?

Answer Source

You can do it using Google api for identifying current timezone.
.Net Fiddle example:

public class Program
{
    public static DateTime GetLocalDateTime(double latitude, double longitude, DateTime utcDate)
    {
        var client = new RestClient("https://maps.googleapis.com");
        var request = new RestRequest("maps/api/timezone/json", Method.GET);
        request.AddParameter("location", latitude + "," + longitude);
        request.AddParameter("timestamp", utcDate.ToTimestamp());
        request.AddParameter("sensor", "false");
        var response = client.Execute<GoogleTimeZone>(request);

        return utcDate.AddSeconds(response.Data.rawOffset + response.Data.dstOffset);
    }

    public static void Main()
    {
        var myDateTime = GetLocalDateTime(33.8323, -117.8803, DateTime.UtcNow);
        Console.WriteLine(myDateTime.ToString());
    }
}

public class GoogleTimeZone 
{
    public double dstOffset { get; set; }
    public double rawOffset { get; set; }
    public string status { get; set; }
    public string timeZoneId { get; set; }
    public string timeZoneName { get; set; }
}

public static class ExtensionMethods 
{
    public static double ToTimestamp(this DateTime date)
    {
        DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        TimeSpan diff = date.ToUniversalTime() - origin;
        return Math.Floor(diff.TotalSeconds);
    }
}

And then you can easily use your GetLocalDateTime(double latitude, double longitude, DateTime utcDate) method as it was shown in the example above:

public static void Main()
{
    var myDateTime = GetLocalDateTime(33.8323, -117.8803, DateTime.UtcNow);
    Console.WriteLine(myDateTime.ToString());
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download