Reputation: 20670
NSDateFormatter *formatter1=[[NSDateFormatter alloc]init];
[formatter1 setDateFormat:@"HHmmss MMddyyyy"];
NSDate *finalDate =[formatter1 dateFromString:testTime];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[lblpickUpTime setText:[formatter stringFromDate:finalDate]];
[formatter release];
[formatter1 release];
where testTime = @"201518 07122011"; and I want the result in 24 hours time
e.g. 20.15 rather than 8:15 PM
and is there any better way to do this?
Upvotes: 10
Views: 13977
Reputation: 15115
Try by setting
[formatter setDateFormat:@"HH:mm"]; // replacement for [formatter setTimeStyle:NSDateFormatterShortStyle];
Alternate method (without using any formatters):
NSRange range;
range.location = 2;
range.length = 2;
NSString *dateString = [NSString stringWithFormat:@"%@:%@",[myString substringToIndex:2],[myString substringWithRange:range]];
Upvotes: 25
Reputation: 5765
If you specify a format instead of using NSDateFormatterShortStyle
, you can have the output in any format you want. For example:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];
[lblpickUpTime setText:[formatter stringFromDate:finalDate]];
[formatter release];
Upvotes: 4