[研究]ASP.NET, WebForm, NodaTime 3.2.2日期與時間處理函式庫套件試用
2025-07-29
官方沒公開 CVE 報告
https://github.com/nodatime/nodatime.org/security/advisories
Noda Time 是一個用於 .NET 的日期與時間處理函式庫,旨在取代 System.DateTime,提供更準確且清晰的 API。其靈感來自於 Java 的 Joda-Time 函式庫。
✅ Noda Time 的優點:
- 明確區分 本地時間 (LocalDateTime)、區域時間 (ZonedDateTime)、不含時區時間 (LocalDate)。
- 內建時區資料庫(tzdb),支援 IANA 時區(例如 "Asia/Taipei")。
- 避免使用 DateTimeKind 混亂(如 Unspecified, Utc, Local)。
- 適合處理複雜日曆邏輯,例如夏令時間轉換。
環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C# + SQL Server 2019 + SQL Server Management Studio (SSMS) 20.2
正在安裝:
System.Runtime.CompilerServices.Unsafe.6.0.0
NodaTime.3.2.2
********************************************************************************
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>目前台北時間:</h2>
<asp:Label ID="lblTaipeiTime" runat="server" Font-Bold="true" Font-Size="Large" />
<h3>輸入 ISO 時間字串(例如:2025-07-29T09:00:00)</h3>
<asp:TextBox ID="txtIsoInput" runat="server" Width="300px" />
<asp:Button ID="btnConvert" runat="server" Text="轉換成台北時間" OnClick="btnConvert_Click" />
<br /><br />
<asp:Label ID="lblConvertedTime" runat="server" ForeColor="DarkGreen" Font-Bold="true" />
</div>
</form>
</body>
</html>
|
Default.aspx.cs
using NodaTime;
using NodaTime.Text;
using System;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// 顯示目前台北時間
var now = SystemClock.Instance.GetCurrentInstant();
var taipeiZone = DateTimeZoneProviders.Tzdb["Asia/Taipei"];
var zonedNow = now.InZone(taipeiZone);
lblTaipeiTime.Text = zonedNow.ToString("yyyy-MM-dd HH:mm:ss z", null);
}
}
protected void btnConvert_Click(object sender, EventArgs e)
{
var input = txtIsoInput.Text.Trim();
// 嘗試解析使用者輸入的 ISO 字串
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd'T'HH:mm:ss");
var parseResult = pattern.Parse(input);
if (!parseResult.Success)
{
lblConvertedTime.Text = "⚠️ 格式錯誤,請輸入合法的 ISO 時間(例如:2025-07-29T09:00:00)";
return;
}
LocalDateTime ldt = parseResult.Value;
var taipeiZone = DateTimeZoneProviders.Tzdb["Asia/Taipei"];
var zoned = ldt.InZoneLeniently(taipeiZone); // 可能跨 DST
lblConvertedTime.Text = $"台北時間:{zoned.ToString("yyyy-MM-dd HH:mm:ss z", null)}";
}
}
}
|
(完)
相關
xx




沒有留言:
張貼留言