在Flex中调用JS的gettime方法获取时间,并将其传递给C#,需要将字符串类型的日期时间转换为DateTime类型。然而,由于字符串中的时区偏移量格式可能不正确,导致直接使用DateTime.ParseExact方法转换失败。/n/n为了解决这个问题,可以尝试使用正则表达式来匹配字符串中的时区偏移量,并将其转换为TimeSpan类型,然后使用DateTimeOffset类型来处理时区信息,最后转换为DateTime类型。/n/n以下代码片段展示了如何使用正则表达式来处理时区偏移量,并进行转换:/n/ncsharp/nstring time = 'Mon Jun 26 09:29:57 UTC+0800 2023';/nRegex regex = new Regex(@'(?<sign>[-+])(?<hours>/d{2})(?<minutes>/d{2})');/nMatch match = regex.Match(time);/nif (match.Success)/n{/n TimeSpan timeSpan = new TimeSpan(int.Parse(match.Groups['hours'].Value), int.Parse(match.Groups['minutes'].Value), 0);/n if (match.Groups['sign'].Value == '-')/n {/n timeSpan = timeSpan.Negate();/n }/n DateTimeOffset dateTimeOffset = DateTimeOffset.ParseExact(time.Replace(match.Value, ''), 'ddd MMM dd HH:mm:ss yyyy', CultureInfo.InvariantCulture);/n dateTimeOffset = dateTimeOffset.ToOffset(timeSpan);/n DateTime dateTime = dateTimeOffset.DateTime;/n // 处理 dateTime/n}/nelse/n{/n // 处理无法匹配时区偏移量的情况/n}/n/n/n这段代码使用正则表达式匹配字符串中的时区偏移量,并将其转换为TimeSpan类型,然后使用DateTimeOffset类型来处理时区信息,最后转换为DateTime类型。/n/n如果仍然无法转换,请仔细检查字符串中的时区偏移量格式,确保其符合规范。

Flex调用JS获取时间并转换为C# DateTime类型

原文地址: https://www.cveoy.top/t/topic/oWdg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录