我一直在尝试编写一个扩展方法,用于在正确的时区和格式中生成带有datetime的字符串。我的代码是:
public static class DateTimeExtension
{
public static string ToZoneString(this DateTime date, string zoneId, string formatter)
{
TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
return TimeZoneInfo.ConvertTime(date, zone).ToString(formatter);
}
public static string ToZoneString(this DateTimeOffset date, string zoneId, string formatter)
{
//in this case all goes well
//TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
//return TimeZoneInfo.ConvertTime(date, zone).ToString(formatter);
//in this case an unexpected error occurs
return date.ToZoneString(zoneId, formatter);
}
}
但是在编译并运行我的ASP.NET MVC项目之后
发生了“w3wp.exe中出现未处理的Microsoft .Net Framework异常”
。为什么会这样?如果我没有在第二个方法中调用第一个方法,只是执行相同的操作,所有方法都正确执行。
答案 0 :(得分:2)
我认为,如果您以这种方式更新第二种方法,它将适合您:
public static string ToZoneString(this DateTimeOffset date, string zoneId, string formatter)
{
//in this case all goes well
//TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
//return TimeZoneInfo.ConvertTime(date, zone).ToString(formatter);
//in this case an unexpected error occurs
return date.DateTime.ToZoneString(zoneId, formatter);
}
但根据您的需要,您可以选择不同的方法从DateTimeOffset获取DateTime(LocalDateTime
,UtcDateTime
)
答案 1 :(得分:0)
你的第二种方法没有打电话给你的第一种方法,它只是再次打电话给你的第二种方法。再次召唤你的第二个。再次召唤你的第二个。依此类推,直到整个过程崩溃为StackOverflowException
。
答案 2 :(得分:0)
你永远不会调用第一种方法。您的第二种方法是调用本身。如果您想调用第一种方法,则需要先将DateTimeOffset
转换为DateTime
。