主頁 > 移動端開發 > 如何在C#專案中處理gasdays?

如何在C#專案中處理gasdays?

2022-05-12 19:44:07 移動端開發

天然氣日定義為 24 小時的時間范圍,從歐洲標準時間 5:00 UTC 開始,到次日 5:00 UTC 結束。在歐洲夏令時期間,它從 4:00 UTC 開始,到次日 4:00 UTC 結束(參見WikipediaACER以獲取英文解釋)。

我需要在應用程式中使用 gas days 才能執行以下操作:

  1. 獲取任何給定 UTC 時間戳的當前 gas day。示例:“2022-03-22 05:00:00”(UTC)應變為“2022-03-22 00:00:00”(加油日)。
  2. 從特定的 gas 日添加和/或減去時間跨度(天、小時等)以獲得新的時間戳,該時間戳也將 DST 考慮在內。例如,這意味著如果我從時間戳“2022-03-29 04:00:00”(UTC)(等于煤氣日“2022-03-29)中減去 7 天,我想得到時間戳” 2022-03-22 05:00:00" (UTC)。

對我來說,這感覺好像“加油日”應該作為類似于時區的東西提供,然后我可以在我的應用程式中使用它,但是嘗試使用DateTimeDateTimeOffset讓我完全不知道我應該做什么這項作業。

誰能指出我必須做的正確方向,以允許我進行上面解釋的計算?是否有一個圖書館可以讓這更容易做?例如,我已經研究過NodaTime,但我在它的檔案中找不到任何能讓我更容易解決這個任務的東西。

uj5u.com熱心網友回復:

我將使用更精確的定義:“加油日”(或者更確切地說“加油時間”,因為這里有一個時間部分)基于德國的當地時區,但偏移了 6 個小時,使得德國的 06:00 為 00:燃氣時間為 00。

正如您在自己的實驗中發現的那樣,自定義時區方法并不那么容易實作,因為轉換都發生在德國的本地日期和時間,即使氣體轉換將值推到不同的日期也是如此。(使用 NodaTime 可能可行,但不能使用TimeZoneInfo.)

考慮到這一點,您需要在德國時間進行所有轉換和操作,然后將它們轉換為 Gas Time。一些擴展方法在這里很有用。解釋性注釋內嵌在代碼中。

public static class GasTimeExtensions
{
    private static readonly TimeZoneInfo GermanyTimeZone =
        TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin");
        // (use "W. Europe Standard Time" for .NET < 6 on Windows)

    private static readonly TimeSpan GasTimeOffset = TimeSpan.FromHours(6);

    /// <summary>
    /// Adjusts the provided <paramref name="dateTimeOffset"/> to Gas Time.
    /// </summary>
    /// <param name="dateTimeOffset">The value to adjust.</param>
    /// <returns>The adjusted value.</returns>
    public static DateTimeOffset AsGasTime(this DateTimeOffset dateTimeOffset)
    {
        // Convert to Germany's local time.
        var germanyTime = TimeZoneInfo.ConvertTime(dateTimeOffset, GermanyTimeZone);
        
        // Shift for Gas Time.
        return germanyTime.ToOffset(germanyTime.Offset - GasTimeOffset);
    }

    /// <summary>
    /// Adjusts the provided <paramref name="dateTime"/> to Gas Time.
    /// </summary>
    /// <param name="dateTime">The value to adjust.</param>
    /// <returns>The adjusted value.</returns>
    public static DateTime AsGasTime(this DateTime dateTime)
    {
        // Always go through a DateTimeOffset to ensure conversions and adjustments are applied.
        return dateTime.ToGasDateTimeOffset().DateTime;
    }

    /// <summary>
    /// Adjusts the provided <paramref name="dateTime"/> to Gas Time,
    /// and returns the result as a <see cref="DateTimeOffset"/>.
    /// </summary>
    /// <param name="dateTime">The value to adjust.</param>
    /// <returns>The adjusted value as a <see cref="DateTimeOffset"/>.</returns>
    public static DateTimeOffset ToGasDateTimeOffset(this DateTime dateTime)
    {
        if (dateTime.Kind != DateTimeKind.Unspecified)
        {
            // UTC and Local kinds will get their correct offset in the DTO constructor.
            return new DateTimeOffset(dateTime).AsGasTime();
        }
        
        // Treat the incoming value as already in gas time - we just need the offset applied.
        // However, we also need to account for values that might be during DST transitions.
        var germanyDateTime = dateTime   GasTimeOffset;
        if (GermanyTimeZone.IsInvalidTime(germanyDateTime))
        {
            // In the DST spring-forward gap, advance the clock forward.
            // This should only happen if the data was bad to begin with.
            germanyDateTime = germanyDateTime.AddHours(1);
        }

        // In the DST fall-back overlap, choose the offset of the *first* occurence,
        // which is the same as the offset before the transition.
        // Otherwise, we're not in a transition, just get the offset.
        var germanyOffset = GermanyTimeZone.GetUtcOffset(
            GermanyTimeZone.IsAmbiguousTime(germanyDateTime)
                ? germanyDateTime.AddHours(-1)
                : germanyDateTime);

        // Construct the Germany DTO, shift to gas time, and return.
        var germanyDateTimeOffset = new DateTimeOffset(germanyDateTime, germanyOffset);
        return germanyDateTimeOffset.ToOffset(germanyOffset - GasTimeOffset);
    }

    /// <summary>
    /// Add a number of calendar days to the provided <paramref name="dateTimeOffset"/>, with respect to Gas Time.
    /// </summary>
    /// <remarks>
    /// A day in Gas Time is not necessarily 24 hours, because some days may contain a German DST transition.
    /// </remarks>
    /// <param name="dateTimeOffset">The value to add to.</param>
    /// <param name="daysToAdd">The number of calendar days to add.</param>
    /// <returns>The result of the operation, as a <see cref="DateTimeOffset"/> in Gas Time.</returns>
    public static DateTimeOffset AddGasDays(this DateTimeOffset dateTimeOffset, int daysToAdd)
    {
        // Add calendar days (with respect to gas time) - not necessarily 24 hours.
        return dateTimeOffset.AsGasTime().DateTime.AddDays(daysToAdd).ToGasDateTimeOffset();
    }
    
    /// <summary>
    /// Add a number of calendar days to the provided <paramref name="dateTime"/>, with respect to Gas Time.
    /// </summary>
    /// <remarks>
    /// A day in Gas Time is not necessarily 24 hours, because some days may contain a German DST transition.
    /// </remarks>
    /// <param name="dateTime">The value to add to.</param>
    /// <param name="daysToAdd">The number of calendar days to add.</param>
    /// <returns>The result of the operation, as a <see cref="DateTime"/> in Gas Time.</returns>
    public static DateTime AddGasDays(this DateTime dateTime, int daysToAdd)
    {
        // Add calendar days (with respect to gas time) - not necessarily 24 hours.
        return dateTime.AsGasTime().AddDays(daysToAdd).AsGasTime();
    }
}

一些使用示例:

  • 轉換特定時間戳

    var test = DateTimeOffset.Parse("2022-03-22T05:00:00Z").AsGasTime();
    Console.WriteLine($"{test:yyyy-MM-ddTHH:mm:sszzz} in Gas Time is 
    {test.UtcDateTime:yyyy-MM-ddTHH:mm:ssZ} UTC.");
    

    輸出:

    2022-03-22T00:00:00-05:00 in Gas Time is 2022-03-22T05:00:00Z UTC.
    
  • 獲取當前氣體時間戳

    var now = DateTimeOffset.UtcNow.AsGasTime();
    Console.WriteLine($"It is now {now:yyyy-MM-ddTHH:mm:sszzz} in Gas Time ({now.UtcDateTime:yyyy-MM-ddTHH:mm:ssZ} UTC).");
    

    輸出:

    It is now 2022-05-10T14:31:56-04:00 in Gas Time (2022-05-10T18:31:56Z UTC).
    
  • 添加絕對時間(小時、分鐘、秒等)

    var start = DateTimeOffset.Parse("2022-03-26T05:00:00Z").AsGasTime();
    var end = start.AddHours(24 * 7).AsGasTime(); // add and correct any offset change
    Console.WriteLine($"Starting at {start:yyyy-MM-ddTHH:mm:sszzz} Gas Time ({start.UtcDateTime:yyyy-MM-ddTHH:mm:ssZ} UTC),");
    Console.WriteLine($"7 x 24hr intervals later is {end:yyyy-MM-ddTHH:mm:sszzz} Gas Time ({end.UtcDateTime:yyyy-MM-ddTHH:mm:ssZ} UTC).");
    

    輸出:

    Starting at 2022-03-26T00:00:00-05:00 Gas Time (2022-03-26T05:00:00Z UTC),
    7 x 24hr intervals later is 2022-04-02T01:00:00-04:00 Gas Time (2022-04-02T05:00:00Z UTC).
    
  • 添加或減去日歷天數(由于 DST 轉換,并非嚴格的 24 小時天數)

    var start = DateTimeOffset.Parse("2022-03-26T05:00:00Z").AsGasTime();
    var end = start.AddGasDays(7); // add and correct any offset change
    Console.WriteLine($"Starting at {start:yyyy-MM-ddTHH:mm:sszzz} Gas Time ({start.UtcDateTime:yyyy-MM-ddTHH:mm:ssZ} UTC),");
    Console.WriteLine($"7 calendar days later is {end:yyyy-MM-ddTHH:mm:sszzz} Gas Time ({end.UtcDateTime:yyyy-MM-ddTHH:mm:ssZ} UTC).");
    

    輸出:

    Starting at 2022-03-26T00:00:00-05:00 Gas Time (2022-03-26T05:00:00Z UTC),
    7 calendar days later is 2022-04-02T00:00:00-04:00 Gas Time (2022-04-02T04:00:00Z UTC).
    

請注意,在最后兩個示例中,我選擇了與您不同的日期,以演示跨越 DST 過渡。

uj5u.com熱心網友回復:

您可以創建一個符合 Gas Day 規則的自定義時區。

由于您提到的規則是基于另一個時區的,因此很容易引入另一個時區的規則,并以此為基礎:

static TimeZoneInfo CreateGasDayTimezone()
{
    // Use CET adjustment rules for daylight saving time
    var cet = TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time");
    var cetAdjustmentRules = cet.GetAdjustmentRules();

    // Create a new timezone offset by 5 hours off UTC, using CET for DST
    var gasday = TimeZoneInfo.CreateCustomTimeZone(
        "Europe/Gas_Day",
        TimeSpan.FromHours(-5),
        "Gas Day", 
        "Gas Day (Standard)", 
        "Gas Day (Daylight)", 
        cetAdjustmentRules);

    return gasday;
}

使用新時區非常簡單:

var date = new DateTime(2020, 1, 1);
var gasdayZone = CreateGasDayTimezone();
var dateAsGasDay = TimeZoneInfo.ConvertTimeFromUtc(date, gasdayZone);
Console.WriteLine(date   " is "   dateAsGasDay   " in gas day");

uj5u.com熱心網友回復:

這是一個快速解決方案,可將您的加油日邏輯實作為附加到該System.DateTime型別的 C# 擴展方法。DateTimeOffset如果您想使用該型別,也可以將其附加到類似的邏輯。

這是代碼:

public static class SpecialDateExtensions
{
    public static DateTime GetGasDay(this DateTime current)
    {
        var datePart = current.Date;
        var gasDayThreshold = datePart.AddHours(5);
        return current > gasDayThreshold ? datePart : datePart.AddDays(-1);
    }
}

static void Main(string[] args)
{
    // usage 
    var now = DateTime.Now;
    var gasday = now.GetGasDay();
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/472632.html

標籤:C# 约会时间 时区 日期时间偏移 节点时间

上一篇:如何使用日期和時間設定plt.xlimit

下一篇:獲取連續周期熊貓的第一個和最后一個日期

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【從零開始擼一個App】Dagger2

    Dagger2是一個IOC框架,一般用于Android平臺,第一次接觸的朋友,一定會被搞得暈頭轉向。它延續了Java平臺Spring框架代碼碎片化,注解滿天飛的傳統。嘗試將各處代碼片段串聯起來,理清思緒,真不是件容易的事。更不用說還有各版本細微的差別。 與Spring不同的是,Spring是通過反射 ......

    uj5u.com 2020-09-10 06:57:59 more
  • Flutter Weekly Issue 66

    新聞 Flutter 季度調研結果分享 教程 Flutter+FaaS一體化任務編排的思考與設計 詳解Dart中如何通過注解生成代碼 GitHub 用對了嗎?Flutter 團隊分享如何管理大型開源專案 插件 flutter-bubble-tab-indicator A Flutter librar ......

    uj5u.com 2020-09-10 06:58:52 more
  • Proguard 常用規則

    介紹 Proguard 入口,如何查看輸出,如何使用 keep 設定入口以及使用實體,如何配置壓縮,混淆,校驗等規則。

    ......

    uj5u.com 2020-09-10 06:59:00 more
  • Android 開發技術周報 Issue#292

    新聞 Android即將獲得類AirDrop功能:可向附近設備快速分享檔案 谷歌為安卓檔案管理應用引入可安全隱藏資料的Safe Folder功能 Android TV新主界面將顯示電影、電視節目和應用推薦內容 泄露的Android檔案暗示了傳說中的谷歌Pixel 5a與折疊屏新機 谷歌發布Andro ......

    uj5u.com 2020-09-10 07:00:37 more
  • AutoFitTextureView Error inflating class

    報錯: Binary XML file line #0: Binary XML file line #0: Error inflating class xxx.AutoFitTextureView 解決: <com.example.testy2.AutoFitTextureView android: ......

    uj5u.com 2020-09-10 07:00:41 more
  • 根據Uri,Cursor沒有獲取到對應的屬性

    Android: 背景:呼叫攝像頭,拍攝視頻,指定保存的地址,但是回傳的Cursor檔案,只有名稱和大小的屬性,沒有其他諸如時長,連ID屬性都沒有 使用 cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATIO ......

    uj5u.com 2020-09-10 07:00:44 more
  • Android連載29-持久化技術

    一、持久化技術 我們平時所使用的APP產生的資料,在記憶體中都是瞬時的,會隨著斷電、關機等丟失資料,因此android系統采用了持久化技術,用于存盤這些“瞬時”資料 持久化技術包括:檔案存盤、SharedPreference存盤以及資料庫存盤,還有更復雜的SD卡記憶體儲。 二、檔案存盤 最基本存盤方式, ......

    uj5u.com 2020-09-10 07:00:47 more
  • Android Camera2Video整合到自己專案里

    背景: Android專案里呼叫攝像頭拍攝視頻,原本使用的 MediaStore.ACTION_VIDEO_CAPTURE, 后來因專案需要,改成了camera2 1.Camera2Video 官方demo有點問題,下載后,不能直接整合到專案 問題1.多次拍攝視頻崩潰 問題2.雙擊record按鈕, ......

    uj5u.com 2020-09-10 07:00:50 more
  • Android 開發技術周報 Issue#293

    新聞 谷歌為Android TV開發者提供多種新功能 Android 11將自動填表功能整合到鍵盤輸入建議中 谷歌宣布Android Auto即將支持更多的導航和數字停車應用 谷歌Pixel 5只有XL版本 搭載驍龍765G且將比Pixel 4更便宜 [圖]Wear OS將迎來重磅更新:應用啟動時間 ......

    uj5u.com 2020-09-10 07:01:38 more
  • 海豚星空掃碼投屏 Android 接收端 SDK 集成 六步驟

    掃碼投屏,開放網路,獨占設備,不需要額外下載軟體,微信掃碼,發現設備。支持標準DLNA協議,支持倍速播放。視頻,音頻,圖片投屏。好點意思。還支持自定義基于 DLNA 擴展的操作動作。好像要收費,沒體驗。 這里簡單記錄一下集成程序。 一 跟目錄的build.gradle添加私有mevan倉庫 mave ......

    uj5u.com 2020-09-10 07:01:43 more
最新发布
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:40:31 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:40:11 more
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:39:36 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:39:13 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:16:23 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:16:15 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:15:46 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:14:53 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:14:08 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:08:34 more