我有一個表T1,其中Id,Name和TimeZone作為列。該TimeZone列具有 IANA (TZDB) 格式,就像America/Chicago
我從中獲取資料T1一樣
response = T1.Where(t => t.Id == 9).Select(rez => new
{
RezName = rez .Name,
Offset = ...
});
在里面Offset我需要在幾分鐘內獲得當前的偏移量(比如 -300,因為America/Chicago它有偏移量 -05)。有沒有辦法在 LINQ 查詢中獲取偏移分鐘數,或者僅通過在選擇后迭代并計算每個元素的本地時間?
uj5u.com熱心網友回復:
正如您最初用 標記您的問題nodatime一樣,以下是您可以如何利用 NodaTime 來解決此問題:
using NodaTime;
...
Instant now = SystemClock.Instance.GetCurrentInstant();
response = T1.Where(t => t.Id == 9)
.Select(rez => new
{
RezName = rez.Name,
TimeZone = rez.TimeZone
})
.AsEnumerable()
.Select(x => new
{
RezName = x.RezName,
Offset = (int) DateTimeZoneProviders.Tzdb[x.TimeZone]
.GetUtcOffset(now).ToTimeSpan().TotalMinutes
});
如果您在 Linux 或 macOS 上使用 .NET,或者如果您在 Windows 上使用 .NET 6 或更高版本,則無需 Noda Time 即可執行此操作:
DateTimeOffset now = DateTimeOffset.UtcNow;
Instant now = SystemClock.Instance.GetCurrentInstant();
response = T1.Where(t => t.Id == 9)
.Select(rez => new
{
RezName = rez.Name,
TimeZone = rez.TimeZone
})
.AsEnumerable()
.Select(x => new
{
RezName = x.RezName,
Offset = (int) TimeZoneInfo.FindSystemTimeZoneById(x.TimeZone)
.GetUtcOffset(now).TotalMinutes
});
另一種選擇是使用TimeZoneConverter中的 `TZConvert.GetTimeZoneInfo ,其代碼與第二個示例類似。
請記住,所有這些都回傳與 UTC 的當前偏移量(以分鐘為單位,正值位于 GMT 以東)。因為America/Chicago,目前-300是因為夏令時生效。當白天結束時,它將回傳-360。
請注意,在上述示例中,時區代碼必須在查詢具體化之后出現,因為像 EF 這樣的 LINQ 提供程式不可能將其轉換為 SQL 查詢。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/453240.html
