簡體   English   中英

NSDate從String返回nil

[英]NSDate from String returning nil

我將日期存儲為字符串,格式為:2018-07-10 21:00:29 +0000

我創建了一個格式化程序,將字符串轉換回日期:

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
[formatter setLocale:[NSLocale currentLocale]];
NSDate *date = [formatter dateFromString:[chore getDate]];

但是,返回的日期始終為零。 有人知道我在做什么錯嗎?

您在dateformat中設置了錯誤的格式。 因此它將始終返回nil值。

下面的方法可以以NSDate格式返回日期。

-(NSDate *)convertDate :(NSString *)date1  //the argument date1 is the string date you used

{   
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z"; // the format which you used in the string date
    [formatter setLocale:[NSLocale currentLocale]]; //This for set the Locale .It is not compulsory.
    NSDate *date = [formatter dateFromString:date1];
    return date;

}

請在此處參考日期格式化程序的日期格式:

您需要將日期格式更新為"yyyy-MM-dd HH:mm:ss Z"

暫無
暫無

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

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