NSDate 的解析时间

Parse Time From NSDate

我正在尝试从看起来像 @"2016-05-12T16:25:55.000Z" 的字符串中获取时间。我试过这样的事情:

NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat       = @"HH:mm";
formatter.timeZone         = [NSTimeZone systemTimeZone];

NSDate *serverDate = [formatter dateFromString:dateString];
NSString* time = [formatter stringFromDate:serverDate];
NSLog(@"Time: %@", time);

但是我的 serverDate 正在返回 null。我不确定我做错了什么。

当您从 NSString 创建 NSDate 时,日期格式必须完全匹配整个字符串。

但您的目标似乎是将时间作为字符串获取。所以只需获取子字符串:

NSString *time = [dateString substringWithRange:NSMakeRange(11, 5)];

当然这不会以任何方式处理时区。如果您希望将原始字符串解析为 NSDate 然后从该日期获取时间,所有这些都需要进行时区调整,那么您需要两种日期格式。一个将原始字符串解析为 NSDate,第二个(您已有的)生成具有所需输出(本例中为时间)的新字符串。

您可以将格式化程序的日期格式 属性 设置为:@"yyyy-MM-dd'T'HH:mm:ssZ",然后使用 NSDateComponents 获取时间值。

首先将你的日期转换为 NSDate

+ (NSDate *) convertDateToNSDateWithGivenFormat: (NSString *) dateStr Format:(NSString*) format
{
    NSDateFormatter *dateFormatterDate = nil;
    NSDate *dateonly = nil;

    if (dateFormatterDate == nil) {
        dateFormatterDate = [[NSDateFormatter alloc] init];
        [dateFormatterDate setDateFormat:format];
    }
    dateonly = [dateFormatterDate dateFromString:[NSString stringWithFormat:@"%@", dateStr]];

    return dateonly;
}

然后使用 NSDate 变量来拆分日期和时间

+ (NSString *) GetFormattedTimeStringForGivenDate:(NSDate *) date
{
    NSString *retStr = nil;
    NSDate *now = date;
    NSDateFormatter *dateFormatterDateOnly = nil;
    NSDateFormatter *dateFormatterTimeOnly = nil;

    if (dateFormatterDateOnly == nil) {
        dateFormatterDateOnly = [[NSDateFormatter alloc] init];
        [dateFormatterDateOnly setDateFormat:@"MM/dd/yyyy"];
    }
    if (dateFormatterTimeOnly == nil) {
        dateFormatterTimeOnly = [[NSDateFormatter alloc] init];
        [dateFormatterTimeOnly setDateFormat:@"hh:mm:ss:a"];
    }
    //if you need date use this
    //retStr  = [NSString stringWithFormat:@"%@", [dateFormatterDateOnly stringFromDate:now]];
    retStr  = [NSString stringWithFormat:@"%@", [dateFormatterTimeOnly stringFromDate:now]];
    return retStr;
}

这里是例子。您可以根据需要更改格式:

   NSDate *myDt = [MyClass convertDateToNSDateWithGivenFormat: @"2016-05-12T16:25:55" Format:@"yyyy-MM-dd'T'HH:mm:ss"];
    NSString *str = [MyClass GetFormattedTimeForGivenDate:myDt];