[C#] 日期時間轉換

  • 155
  • 0
  • 2022-11-14

日期時間轉換

    DateTime testDateTime = new DateTime(2022, 12, 10, 10, 50, 30);
    testDateTime.Dump("《測試用》日期時間(DateTime)");

    TimeOnly testTimeOnly = TimeOnly.Parse("10:00 PM");
    testTimeOnly.Dump("《測試用》時間(TimeOnly)");

    DateOnly testDateOnly = new DateOnly(2022, 11, 11);
    testDateOnly.Dump("《測試用》日期(DateOnly)");

    // --------------------------------------------------------------------------

    DateOnly dateOnly = DateOnly.FromDateTime(testDateTime);
    testDateOnly.ToString().Dump("將DateTime轉換成DateOnly型別");

    TimeOnly timeOnly = TimeOnly.FromDateTime(testDateTime);
    timeOnly.ToLongTimeString().Dump("將DateTime轉換成TimeOnly型別");
    
    DateTime testDateTime2 = testDateOnly.ToDateTime(TimeOnly.Parse("10:00 PM"));
    testDateTime.Dump("將DateOnly轉換成DateTime型別");

    TimeSpan timeSpan = testTimeOnly.ToTimeSpan();
    timeSpan.Dump("將TimeOnly轉換成TimeSpan型別 (應該沒有這種使用案例或情境)");
    
    DateTime dt = DateTime.MinValue.AddSeconds(testTimeOnly.ToTimeSpan().TotalSeconds);
    dt.Dump("將TimeOnly轉換成DateTime型別 (應該沒有這種使用案例或情境)");

 參考資料

https://www.facebook.com/groups/DotNetUserGroupTaiwan/permalink/3025770601049371/