簡體   English   中英

使用NSDateFormatter將NSString解析為NSDate

[英]Parsing NSString to NSDate using NSDateFormatter

我有這樣的字符串:“ TEST,2013年10月22日,美國東部時間下午1點59分”,我正在嘗試設置以下解析規則:

[formatter setDateFormat: @"EEE, dd MMM yyyy hh:mm a z"];

但這在我執行時返回nil

[formatter dateFromString: @"Tue, 22 Oct 2013 1:59 pm EEST"];

這種格式正確的正則表達式是什么?

 NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"EEE, dd MMM yyyy hh:mm a zzz"];
    [formatter setLocale:locale];
    NSDate* date = [formatter dateFromString:@"Tue, 22 Oct 2013 1:59 PM EEST"];
    NSLog(@"date: %@",date);

O/P:-date: 2013-10-22 10:59:00 +0000

hh是帶填充小時(在您的情況下為“ 01”),但是您的字符串沒有帶填充小時(僅為“ 1”),因此應改為h

您可以在下面看到不同格式組件的實際示例( 此GitHub gist的輸出)。 格式化的日期是1987-08-27 15:24:03

format  result
--------------
    yy  87
  yyyy  1987
     M  8
    MM  08
   MMM  Aug
  MMMM  August
    dd  27
    HH  15
    hh  03    // <--.
     h  3     // <--'--- note the difference
     a  PM
    mm  24
     m  24
    ss  03
     s  3

暫無
暫無

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

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