iphone: NSDateFormatter how to show time in 24 hours format?
13,954
Solution 1
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]];
Solution 2
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];
Author by
Azhar
.net / iOS / Android / Windows Mobile/ React-native Optimization Optimization Optimization
Updated on June 28, 2022Comments
-
Azhar almost 2 years
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?
-
Azhar over 12 yearsI only want time not the date
-
Azhar over 12 yearswhat about my second qutions that is there any better way to do this conversion as I made two formatters?
-
Akshay over 12 yearsYou can change the format of the 1st formatter itself.
[formatter1 setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];
. No need for the 2nd formatter. -
KingofBliss over 12 years@azar two conversion is must since u are converting a datestring on one format to another..
-
KingofBliss over 12 years@akshay he is not converting from a date.. his input is also a string.. so your solution wont work
-
KingofBliss over 12 years@azar: you can trim the first four char of the string.. if the time 1:00 am is come as 0100, then it would fine
-
Akshay over 12 years@iAnand: The 2nd conversion is from a date to a string. I don't think it won't work.
-
KingofBliss over 12 years@Akshay: it will work.. bt he want only time.. that i have answer.. then he want to know is there any alternative for not using two formatter.
-
Flexicoder over 10 yearsPlease note that if the user has 24 hour clock turned off on the device it will always return 8:15 PM, regardless of the format string you supply - Apple Docs