簡體   English   中英

iOS9升級后,NSDateFormatter.dateFromString返回null

[英]NSDateFormatter.dateFromString is returning null after iOS9 upgrade

我的一個應用程序在剛剛升級到iOS9的設備上運行后出現問題(應用程序的目標是8.1)。

該應用程序在iOS9之前正常運行,但是,在僅在設備上升級到iOS9后,會出現以下問題。

下面名為'anObsDate'的變量現在返回null。 我不知道為什么。 似乎主機設備上的iOS9獨立升級已經觸發了這個問題。

NSDate *anObsDate = [[self bomDateFormatter] dateFromString:[anObs timeStamp]];

當我使用以下調試運行應用程序時,我們有這個輸出:

     NSLog(@"Timestamp %@", [anObs timeStamp]);
     NSLog(@"Formatter %@", [self bomDateFormatter]);
     NSDate *anObsDate = [[self bomDateFormatter] dateFromString:[anObs timeStamp]];

Timestamp 2015-09-17 00:01:10
Formatter <NSDateFormatter: 0x7fe7abc653c0>

我將日期格式化程序設置如下:

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_AU"];
NSDateFormatter *countDownFormatter = [[NSDateFormatter alloc] init];
[countDownFormatter setLocale:locale];
[countDownFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Melbourne"]];
[countDownFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss"];
return countDownFormatter;

再說清楚一點,如果我在iOS9設備上運行我的應用程序,一切正常,dateFromString返回一個NSDate。 升級到iOS9后,dateFromString返回null。

有什么建議?

謝謝。

似乎NSDateFormatter在iOS 9中的行為發生了變化,因此日期格式中的單引號字符必須與字符串中的字符完全匹配。 以前它會接受任何字符(搜索文檔,但找不到任何提及此更改)。

時間戳字符串缺少以日期格式定義的“T”。 嘗試將日期格式更改為:

// Note the "T" has been removed
[countDownFormatter setDateFormat:@"yyyy'-'MM'-'dd' 'HH':'mm':'ss"];

您的另一個選擇是將“T”添加到時間戳字符串中:

// Note the "T" has been added
2015-09-17T00:01:10

這應該與以前版本的iOS向后兼容。

這解決了我的問題。 你也可以使用它。

在目標C中:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];   
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

在Swift中:

let dateFormatter = NSDateFormatter()    
dateFormatter.locale =  NSLocale(localeIdentifier: "en_US_POSIX")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM