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

C#中字符串转DateTime时毫秒末尾零不显示的问题

解决DateTime变量输出时保留三位毫秒(含末尾零)的问题

核心问题说明

你遇到的不是DateTime变量没保留完整毫秒,而是输出/序列化时的默认格式省略了末尾的零。DateTime.TryParse或ParseExact解析"2021-11-19T19:45:30.810Z"后,变量datefr的Millisecond属性实际是810,只是默认格式化输出时会自动去掉末尾无意义的零。

具体解决方案

1. 手动格式化输出(日志/直接字符串传递场景)

输出时强制指定包含三位毫秒的格式字符串,用fff占位符(代表三位毫秒,不足补零):

// 示例:格式化时保留三位毫秒和时区偏移
string formattedDate = datefr.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz", CultureInfo.InvariantCulture);
// 输出结果:"2021-11-19T19:45:30.810+05:30"
  • fff:固定三位毫秒,末尾零会保留
  • zzz:输出带符号的时区偏移(如+05:30)
  • 必须指定CultureInfo.InvariantCulture避免因系统区域设置导致格式异常

2. API序列化场景(JSON传递)

如果是通过JSON序列化把DateTime传给API,需要配置序列化工具的日期格式:

(1)Newtonsoft.Json(Json.NET)

在序列化配置中指定日期格式:

var settings = new JsonSerializerSettings
{
    DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffzzz",
    Culture = CultureInfo.InvariantCulture
};
string json = JsonConvert.SerializeObject(yourApiRequestModel, settings);
(2)System.Text.Json

配置JsonSerializerOptions强制日期格式:

var options = new JsonSerializerOptions
{
    WriteIndented = true,
    Converters = {
        new DateTimeConverterUsingDateTimeFormat("yyyy-MM-ddTHH:mm:ss.fffzzz")
    }
};
string json = JsonSerializer.Serialize(yourApiRequestModel, options);

// 自定义转换器实现
public class DateTimeConverterUsingDateTimeFormat : JsonConverter<DateTime>
{
    private readonly string _format;
    public DateTimeConverterUsingDateTimeFormat(string format) => _format = format;
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        => DateTime.ParseExact(reader.GetString()!, _format, CultureInfo.InvariantCulture);
    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        => writer.WriteStringValue(value.ToString(_format, CultureInfo.InvariantCulture));
}

3. 验证解析是否正确

可以先打印datefr.Millisecond确认变量本身已保留完整毫秒值:

Console.WriteLine(datefr.Millisecond); // 输出:810

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:27:24