如何获得(MM/dd/yyyy hh:MM a)格式的日期和时间?

Ank*_*han 3 iphone cocoa-touch objective-c nsdate ios4

在我的应用程序中,我必须显示日期和时间这样,

10/19/2011 3pm

目前我写这个代码,

NSDateFormatter *formatar=[[NSDateFormatter alloc] init];       
[formatar setDateFormat:@"MM/dd/YYYY   HH:mm a"];
[formatar setTimeStyle:NSDateFormatterShortStyle];
NSString *st=[formatar stringFromDate:[NSDate date]];
Run Code Online (Sandbox Code Playgroud)

但是以这种格式获取日期:

10/19/2011 15.00

那么,我怎么能在2011年10月19日下午3点格式中得到它?

Emp*_*ack 11

您需要对日期格式进行一些小的更改,以使其按您的需要工作.

1.您的日期格式应仅包含小时(单位数)和无分钟.

"MM/dd/YYYY H a" // Still "a" wouldn't not work here
Run Code Online (Sandbox Code Playgroud)

2.小​​时应为12小时格式,"h"不是"H",以便"a"工作.最后,删除"h""a"之间的空格.

"MM/dd/YYYY ha" // Now you will get what you want!
Run Code Online (Sandbox Code Playgroud)