How to print the time with AM/PM format in iPhone?
12,870
Solution 1
You could use this document for more information NSDateFormatter Class Reference .An example could be:
NSDate* date = [NSDate date];
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
[formatter setTimeStyle:NSDateFormatterFullStyle];
NSLog(@"date=%@",[dateFormatter stringFromDate:date]);
Solution 2
Use below lines of code
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"hh:mm a"];
NSString *str_date = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"str_date:%@",str_date);
Solution 3
You can set your DateFormatter amSymbol
and pmSymbol
as follow:
Xcode 8.3 • Swift 3.1
let formatter = DateFormatter()
formatter.dateFormat = "h:mm a 'on' MMMM dd, yyyy"
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
let dateString = formatter.string(from: Date())
print(dateString) // "4:44 PM on June 23, 2016\n"
Edit: Objective C Code
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.timeZone = [NSTimeZone systemTimeZone];
df.AMSymbol = @"AM";
df.PMSymbol = @"PM";
df.dateFormat = "h:mm a 'on' MMMM dd, yyyy"
NSString *stringDate = [df stringFromDate:dateFromString];
Ref link: https://stackoverflow.com/a/31469237/2905967
Solution 4
Date to String
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@“dd-MMM”];
cell.dateLabel.text = [formatter stringFromDate:item.pubDate]
Date Format Symbols The table from the unicode date formatting page should be enough for you to build your own desired date format string…
Pattern Result (in a particular locale)
yyyy.MM.dd G ‘at’ HH:mm:ss zzz 1996.07.10 AD at 15:08:56 PDT
EEE, MMM d, ‘’yy Wed, July 10, ‘96
h:mm a 12:08 PM
hh ‘o’‘clock’ a, zzzz 12 o’clock PM, Pacific Daylight Time
K:mm a, z 0:00 PM, PST
yyyyy.MMMM.dd GGG hh:mm aaa 01996.July.10 AD 12:08 PM
Hope this is useful to someone out there.
Use the following link for more datails.
http://benscheirman.com/2010/06/dealing-with-dates-time-zones-in-objective-c/
this really helped me. It was really easy.
Author by
RJ168
Updated on June 27, 2022Comments
-
RJ168 almost 2 years
I want to print the time from date picker but with the AM/PM. I can print the time, but it never prints the AM/PM. How can I do this?