如何更简便地将拼接后的日期时间转换为UTC标准格式?
问题描述
我的程序会接收两个输入值:
EDate = "20240328"; ETime = "145222"
二者本质是交易的时间戳,需要转换为如下格式:
2024-03-28T19:52:22.000Z
我目前找到的实现方式如下,虽然能得到正确结果,但感觉不够简洁:
CultureInfo provider = CultureInfo.InvariantCulture; DateTime dateValue; String format = "yyyy-MM-dd\\THH:mm:ss:fff\\Z"; string EDate = "20240328"; string ETime = "145222"; string dtString = String.Concat(EDate, ETime); int y = Convert.ToInt32(dtString.Substring(0,4)); int mm = Convert.ToInt32(dtString.Substring(4,2)); int dd = Convert.ToInt32(dtString.Substring(6,2)); int hh = Convert.ToInt32(dtString.Substring(8,2)) + 5; // 我们的服务器使用中部时间 int m = Convert.ToInt32(dtString.Substring(10,2)); int ss = Convert.ToInt32(dtString.Substring(12,2)); dateValue = new DateTime(y, mm, dd, hh, m, ss); // 输出结果:2024-03-28T19:52:22.000Z Console.WriteLine(dateValue.ToString(format));
请问有没有更简便的实现方法?
简化实现方案
肯定有更省事的写法,核心就是用DateTime.ParseExact直接解析拼接后的时间字符串,再处理时区转换,最后格式化输出就行:
方案1:和原逻辑对齐的简化写法
直接用解析方法替代手动拆分字符串的操作,代码更紧凑:
string EDate = "20240328"; string ETime = "145222"; // 拼接成yyyyMMddHHmmss格式的字符串 string rawTime = $"{EDate}{ETime}"; // 直接解析成DateTime DateTime centralTime = DateTime.ParseExact(rawTime, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); // 加上5小时转成UTC(和你原来的逻辑一致) DateTime utcTime = centralTime.AddHours(5); // 格式化为目标格式 string result = utcTime.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture); Console.WriteLine(result); // 输出:2024-03-28T19:52:22.000Z
方案2:适配夏令时的严谨写法
如果你们服务器用的是美国中部时间,要注意夏令时的问题(每年3-11月偏移是5小时,其他时候是6小时),手动加5小时会在非夏令时出错,用TimeZoneInfo自动处理更靠谱:
string EDate = "20240328"; string ETime = "145222"; string rawTime = $"{EDate}{ETime}"; DateTime centralTime = DateTime.ParseExact(rawTime, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); // 获取美国中部时区信息 TimeZoneInfo centralZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"); // 自动转换为UTC时间 DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(centralTime, centralZone); // 格式化输出 string result = utcTime.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture); Console.WriteLine(result); // 输出:2024-03-28T19:52:22.000Z
为啥这两种写法更好?
- 不用手动截取字符串、转数字,代码量少一半,可读性也更高。
- 方案2能自动适配夏令时的时区偏移,避免时间转换错误,适合长期使用。
内容的提问来源于stack exchange,提问作者MB34
相关产品推荐
相关产品推荐

