我正在编写一个应用程序,它应该根据您提供的坐标(纬度和经度)给出当地时间。
我只知道有两种方法可以做到这一点:
第一:获取时区名称,然后找到它的本地时间。第二:使用 Google API 并接收时间作为偏移量和 UTC 而不是本地。
我决定使用第一种方法,因为看起来更容易,所以我决定使用 GeoTimeZone 来获取时区...问题是我不知道如何获取该时区的本地时间...这里是我为获取 TimeZone 名称而编写的代码。
string tz = TimeZoneLookup.GetTimeZone(lat, lon).Result;
Run Code Online (Sandbox Code Playgroud)
变量lat&lon当然是坐标。
谢谢!
编辑:我的问题是如何在该时区获取 LocalTime?
Éri*_*ron 14
这是我的解决方案。它可以离线工作(因此无需调用 api)。它速度很快,并且这些软件包在 Nuget 上被广泛使用和提供。
string tzIana = TimeZoneLookup.GetTimeZone(lat, lng).Result;
TimeZoneInfo tzInfo = TZConvert.GetTimeZoneInfo(tzIana);
DateTimeOffset convertedTime = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzInfo);
Run Code Online (Sandbox Code Playgroud)
您可以使用 Google api 来识别当前时区。
.Net 小提琴示例:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后您可以轻松使用您的GetLocalDateTime(double latitude, double longitude, DateTime utcDate)方法,如上例所示:
public static void Main()
{
var myDateTime = GetLocalDateTime(33.8323, -117.8803, DateTime.UtcNow);
Console.WriteLine(myDateTime.ToString());
}
Run Code Online (Sandbox Code Playgroud)