Flex 与 C# 之间的时间转换:解析 'Mon Jun 26 08:56:33 UTC+0800 2023' 格式的时间字符串
Flex 与 C# 之间的时间转换:解析 'Mon Jun 26 08:56:33 UTC+0800 2023' 格式的时间字符串
在 Flex 中,使用 getvardatetime() 方法获取的时间字符串格式为 'Mon Jun 26 08:56:33 UTC+0800 2023'。将该字符串传递到 C# 代码后,需要将其转换为 DateTime 类型。
转换方法
在 C# 中,可以使用 DateTime.ParseExact() 方法将字符串转换为 DateTime 类型,并指定格式字符串。
方法一:使用 'UTCzzz' 格式
string time = 'Mon Jun 26 08:56:33 UTC+0800 2023';
DateTime dateTime = DateTime.ParseExact(time, 'ddd MMM dd HH:mm:ss UTCzzz yyyy', CultureInfo.InvariantCulture);
如果上述方法报错,可能是因为字符串中的 '+' 符号表示时区偏移量,而 'UTCzzz' 格式无法解析它。
方法二:使用 'zzz' 格式
string time = 'Mon Jun 26 08:56:33 UTC+0800 2023';
DateTime dateTime = DateTime.ParseExact(time, 'ddd MMM dd HH:mm:ss zzz yyyy', CultureInfo.InvariantCulture);
方法三:替换 '+' 符号
如果仍然报错,可以尝试先将字符串中的 '+' 符号替换为 UTC 格式的时区偏移量,再进行转换。
string time = 'Mon Jun 26 08:56:33 UTC+0800 2023';
time = time.Replace('+', 'UTC+').Replace('-', 'UTC-');
DateTime dateTime = DateTime.ParseExact(time, 'ddd MMM dd HH:mm:ss UTCzzz yyyy', CultureInfo.InvariantCulture);
注意:
- 确保格式字符串与原始字符串的格式一致。
- 如果字符串中的 '+' 号表示时区偏移量,可以使用 'zzz' 格式来表示时区偏移量。
- 如果 '+' 号不表示时区偏移量,可以将其去掉。
- 使用
CultureInfo.InvariantCulture来避免文化差异导致的错误。
原文地址: https://www.cveoy.top/t/topic/oWac 著作权归作者所有。请勿转载和采集!