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

C# 如何将 DateTime 格式化为带四位数字时区偏移的指定字符串

解决方案

你可以通过拆分日期时间部分和时区偏移部分分别格式化后拼接实现,同时指定固定区域文化避免本地化问题,代码如下:

using System.Globalization;

// 方法1:使用DateTime实现
DateTime now = DateTime.Now;
// 格式化日期时间主体部分,固定用英文区域文化保证周、月缩写为英文
string datetimePart = now.ToString("ddd, dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture);
// 单独处理时区偏移,移除多余冒号
string offsetPart = now.ToString("zzz", CultureInfo.InvariantCulture).Replace(":", "");
string result = $"{datetimePart} {offsetPart}";

// 方法2:使用DateTimeOffset实现,逻辑更严谨,不会误修改时间部分的冒号
DateTimeOffset nowOffset = DateTimeOffset.Now;
string datetimePart2 = nowOffset.ToString("ddd, dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture);
string offsetPart2 = $"{nowOffset.Offset.Hours:+00;-00}{nowOffset.Offset.Minutes:00}";
string result2 = $"{datetimePart2} {offsetPart2}";

注意事项

  • 如果需要输出UTC时间,将DateTime.Now替换为DateTime.UtcNow、DateTimeOffset.Now替换为DateTimeOffset.UtcNow即可,时区部分会自动输出+0000。
  • 必须传入CultureInfo.InvariantCulture参数,否则在非英文区域的系统中,星期、月份的缩写会生成本地语言,不符合格式要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:57:03