从Date字符串显示时间

时间:2014-02-12 05:08:48

标签: ios objective-c date

我有以下格式的时间字符串(ISO 8601):

 start = "1900-01-01T11:30:00"
 stop = 1900-01-01T21:30:00

从上面的字符串我需要显示这样的时间:

Starting Time : 11:30a.m
Stopping Time : 09:30p.m

为此我使用下面的代码创建了一个NSDate,但我认为它以GMT格式显示时间。

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
date = [dateFormatter dateFromString:opening];
stopTime = date;

//Output of above code : Date = 1900-01-01 15:36:40 +0000

如何从ISO 8601时间字符串中获取开始和结束时间字符串?我是否需要依赖String操作而不是使用iOS NSDateformatter

2 个答案:

答案 0 :(得分:2)

检查

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];   
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];

NSDate *currentDate = [NSDate date];
NSString *iso8601valueStr = [dateFormatter stringFromDate:currentDate];

答案 1 :(得分:2)

试试这个,

NSString *start = @"1900-01-01T11:30:00";
NSString *stop = @"1900-01-01T21:30:00";
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *sDate = [dateFormatter dateFromString:start];
NSDate *eDate = [dateFormatter dateFromString:stop];

[dateFormatter setDateFormat:@"hh:mm a"];
start = [dateFormatter stringFromDate:sDate];
stop = [dateFormatter stringFromDate:eDate];

NSLog(@"Starting Time : %@", start);
NSLog(@"Stopping Time : %@", stop);

输出将是

2014-02-12 10:55:13.931 [950:a0b] Starting Time : 11:30 AM
2014-02-12 10:55:13.932 [950:a0b] Stopping Time : 09:30 PM