You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中对24小时制时间进行XML序列化与反序列化?

C# XML序列化DateTime为无秒数的24小时制时间

默认的[XmlElement(DataType = "time")]会遵循XML Schema标准输出带秒(甚至毫秒)的时间格式,无法直接得到10:00这种无秒的24小时制格式。你可以通过代理属性的方式实现需求,具体步骤如下:

  1. 给原DateTime属性添加[XmlIgnore]特性,让它不参与XML序列化:
using System.Xml.Serialization;
using System.Globalization;

// 忽略原DateTime属性的序列化
[XmlIgnore]
public DateTime CurrentMeetingTime { get => _CurrentMeetingTime; set => _CurrentMeetingTime = value; }
private DateTime _CurrentMeetingTime;
  1. 创建一个字符串类型的代理属性,指定XML元素名称为原属性名,在get方法中按HH:mm格式输出时间,set方法中解析字符串还原为DateTime:
// 代理属性,负责XML的序列化与反序列化
[XmlElement("CurrentMeetingTime")]
public string CurrentMeetingTimeString
{
    get => _CurrentMeetingTime.ToString("HH:mm", CultureInfo.InvariantCulture);
    set => _CurrentMeetingTime = DateTime.ParseExact(value, "HH:mm", CultureInfo.InvariantCulture);
}

说明

  • HH:mm格式符对应24小时制的小时(00-23)和分钟,不会包含秒数;
  • 使用CultureInfo.InvariantCulture可以避免因系统区域设置导致的格式解析错误;
  • 反序列化时,ParseExact能严格按照指定的HH:mm格式解析XML中的时间字符串,还原为DateTime对象(日期部分会默认设为当前日期,若需要指定固定日期可自行调整)。

内容的提问来源于stack exchange,提问作者Andrew Truckle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 11:40:02