Skip to content

Instantly share code, notes, and snippets.

@fgheysels
Last active May 4, 2021 21:46
Show Gist options
  • Save fgheysels/6171f6ee02838fce76c82e71493f0f85 to your computer and use it in GitHub Desktop.
Save fgheysels/6171f6ee02838fce76c82e71493f0f85 to your computer and use it in GitHub Desktop.
Calculate local time from UTC time based on GPS coordinates

Description

This gist is a code sample which shows how we can determine the current local time for a location, using the GPS coordinates for that location. It makes use of the GeoTimeZone NuGet package.

using System;
using GeoTimeZone;
using TimeZoneConverter;
namespace TimeZoneDetermination
{
class Program
{
static void Main(string[] args)
{
// This code snippet makes use of the GeoTimeZone and TimeZoneConverter
// libraries that are available via GitHub.
// Get the TimeZone that is valid for the specified coordinates and convert the
// resulting TimeZone to a TimeZoneInfo object.
TimeZoneResult timeZone = TimeZoneLookup.GetTimeZone(50.839686, 3.626073);
TimeZoneInfo timeZoneInfo = TZConvert.GetTimeZoneInfo(timeZone.Result);
// Use the information to calculate the local time for that TimeZone, given an UTC date/time
DateTimeOffset utcNow = DateTimeOffset.UtcNow;
DateTimeOffset localTimeNow = TimeZoneInfo.ConvertTimeFromUtc(utcNow.DateTime, timeZoneInfo);
Console.WriteLine($"UTC now: {utcNow}");
Console.WriteLine($"LT now: {localTimeNow}");
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="GeoTimeZone" Version="4.0.0" />
<PackageReference Include="TimeZoneConverter" Version="3.2.0" />
</ItemGroup>
</Project>
@fgheysels
Copy link
Author

fgheysels commented Jul 20, 2020

This gist displays how we can determine the current local time for a specified gps location.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment