Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's my solution. It works offline (so no call to an api). It's fast and the packages are widely used and available on Nuget.

string tzIana = TimeZoneLookup.GetTimeZone(lat, lng).Result;
TimeZoneInfo tzInfo = TZConvert.GetTimeZoneInfo(tzIana);
DateTimeOffset convertedTime = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzInfo);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...