尝试在 iOS6 中运行它(iOS6 之前没有测试过):
NSDateFormatter *julianDayDateFormatter = nil;
julianDayDateFormatter = [[NSDateFormatter alloc] init];
[julianDayDateFormatter setDateFormat:@"g"];
for (NSString *timeZone in [NSTimeZone knownTimeZoneNames]) {
julianDayDateFormatter.timeZone = [NSTimeZone timeZoneWithName: timeZone];
NSDate *date = [julianDayDateFormatter dateFromString:[NSString stringWithFormat:@"%d", 2475213]];
if (date == nil)
NSLog(@"timeZone = %@", timeZone);
}
你会得到以下输出:
America/Bahia
America/Campo_Grande
America/Cuiaba
America/Sao_Paulo
谁能解释为什么当 NSDateFormatter 设置为儒略日数时这四个时区的行为如此?所有其他时区使 NSDateFormatter 返回实际的 NSDates。
最佳答案
我有一个怀疑。只是一种怀疑,但相当强烈。
该值表示 2064 年 10 月 19 日。巴西时区采用夏令时从本地午夜开始 - 这是他们的时钟向前走的时间,因此午夜本身并不存在。 10 月 19 日就是其中之一。
这里有一些使用 Noda Time 的示例代码,我的 .NET 日期/时间 API。它会检查它所知道的每个时区的一天的开始时间是否实际上是午夜:
using System;
using NodaTime;
class Test
{
static void Main()
{
var localDate = new LocalDate(2064, 10, 19);
var provider = DateTimeZoneProviders.Tzdb;
foreach (var id in provider.Ids)
{
var zone = provider[id];
var startOfDay = zone.AtStartOfDay(localDate).LocalDateTime.TimeOfDay;
if (startOfDay != LocalTime.Midnight)
{
Console.WriteLine(id);
}
}
}
}
这会产生一个非常相似的列表:
America/Bahia
America/Campo_Grande
America/Cuiaba
America/Sao_Paulo
Brazil/East
我怀疑巴西/东部可能是 America/Sao_Paolo 的别名,这就是为什么它不在您的列表中。
无论如何,回到您的儒略日问题 - 我怀疑格式化程序总是希望返回一个 NSDate *
,它是在本地午夜。 2064 年 10 月 19 日在这些时区中不存在存在...因此它返回 nil。我个人建议它应该返回 1am 值,但是嘿...
关于objective-c - 为什么 NSDateFormatter 为这 4 个时区返回 nil 日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12922645/