【问题标题】:Convert NSString to NSDate and timeZone?将 NSString 转换为 NSDate 和 timeZone?
【发布时间】:2014-05-22 02:09:10
【问题描述】:

我一直在绞尽脑汁没有运气。有人可以告诉我如何转换这个字符串:

 NSString *dateTimeStr =[[self.responseArray objectAtIndex:indexPath.row]objectForKey:@"date_time"];

2014-04-13T17:00:00+11:0

变成NSDate?和时间格式?

如何将此日期转换为时间格式?

这是我的代码:

NSString *dateTimeStr =[[self.responseArray objectAtIndex:indexPath.row]objectForKey:@"date_time"];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];

[dateFormatter setDateFormat:@"yyyy-MM-ddHH:mm:ss"];

NSDate *date = [dateFormatter dateFromString:dateTimeStr];

NSLog(@"date %@", date);

NSTimeInterval seconds = [date timeIntervalSinceReferenceDate];

在控制台中

NSLog(@"seconds==> %f", seconds);

我有时间以毫秒为单位,那么我如何取出minutes/hours/

【问题讨论】:

  • 你的意思是你需要将字符串转换为日期,而不是日期转换为时间格式。
  • @AnoopVaidya 我需要将我的字符串转换为 timeFormat,实际上我想获取我当前时间和 json 响应 nsstring 之间的差异,这样我就可以在 1 小时前这样的分钟/小时内得到结果
  • @AnoopVaidya 我想从该字符串中获取秒/分/小时。

标签: objective-c nsstring nsdate nsdateformatter


【解决方案1】:
NSString *dateString = @"2014-04-13T17:00:00+11:00";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];

NSDate *date = [dateFormatter dateFromString:dateString];

NSDateComponents *dateComponents = [[NSCalendar currentCalendar]
                                    components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit
                                    fromDate:date];

NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];

【讨论】:

    猜你喜欢
    • 2018-03-10
    • 2011-04-24
    • 2017-04-23
    • 2021-09-11
    • 2016-09-01
    • 2013-01-16
    相关资源
    最近更新 更多