I need to convert this date format @"P18Y9M4DT11H9M8S"
(18 years, 9 month, 4 days, 11 hours, 9 minutesand 8s) to NSDate I can do this using an algorithm but I think there is an easy way to do it.
Asked
Active
Viewed 83 times
-1

rmaddy
- 314,917
- 42
- 532
- 579

viniciusmo
- 974
- 2
- 10
- 15
-
1Any information about where you got that format from? – Peterdk Mar 25 '14 at 17:12
-
As a result of a web service. – viniciusmo Mar 25 '14 at 17:19
-
That's an ["ISO 8601 Duration"](http://en.wikipedia.org/wiki/ISO_8601#Durations) and describes the length of a time interval and not an absolute point in time. So converting that to NSTimeInterval or perhaps NSDateComponents would make more sense ... – Martin R Mar 25 '14 at 17:20
2 Answers
1
Try:
NSString *myDate = @"P18Y9M4DT11H9M8S";
myDate = [myDate stringByReplacingOccurrencesOfString:@"P" withString:@""];
myDate = [myDate stringByReplacingOccurrencesOfString:@"Y" withString:@"-"];
myDate = [myDate stringByReplacingOccurrencesOfString:@"M" withString:@"-"];
myDate = [myDate stringByReplacingOccurrencesOfString:@"D" withString:@"-"];
myDate = [myDate stringByReplacingOccurrencesOfString:@"T" withString:@" "];
myDate = [myDate stringByReplacingOccurrencesOfString:@"H" withString:@"-"];
myDate = [myDate stringByReplacingOccurrencesOfString:@"S" withString:@""];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy/MM/dd HH/mm/ss"];
NSDate *date = [f dateFromString:myDate];
NSLog(@"date = %@", date);

Gabriel.Massana
- 8,165
- 6
- 62
- 81
0
Use NSDateformattet and set the format and maybe some ither options. Then call -dateFromString. See the link for more detailed info: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW7

Joride
- 3,722
- 18
- 22