简体   繁体   中英

How to specify the NSDate Format in Iphone app?

I am trying to make a date format in such a manner hours.minutes day/month/year

I have uses this code :

NSDateFormatter *formatter =[[NSDateFormatter alloc] init];

NSDate *dateAndtime = [NSDate date];

[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateStyle:NSDateFormatterShortStyle];
//[formatter setTimeStyle:NSDateFormatterShortStyle];

NSString* dateforBD=[[NSString alloc]init];
dateforBD =[formatter stringFromDate:dateAndtime];

But this code not give me my format.

Also i have tried this code:

NSLocale *locale = [NSLocale currentLocale];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease]; 
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:@"E MMM d yyyy" 
                        options:0 locale:locale];

[formatter setDateFormat:dateFormat];
[formatter setLocale:locale];

It's also give me different format. How can i achieve the required format means 13.10 21/4/2011

All the formats return in month before date. May i have used wrong way for this ?

Thanks in advance.

     NSDate *today = [NSDate date];
     NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
     [dateFormat setDateFormat:@"MM/dd/yyyy hh:mma"];
     NSString *dateString = [dateFormat stringFromDate:today];
     NSLog(@"date: %@", dateString);
     [dateFormat release];

To explore more visit http://www.stepcase.com/blog/2008/12/02/format-string-for-the-iphone-nsdateformatter/

Hope it helps.

用于月份使用前的日期-

[dateFormat setDateFormat:@"dd/MM/yyyy hh:mm"];

As specified in Apple's NSDateFormatter reference, the NSDateFormatter uses Unicode Date Format Patterns .

According to the unicode patterns, you would need the following pattern to achieve " 13.10 21/4/2011 ":

hh:mm dd/MM/yyyy

So you would use this code:

NSDate *dateAndtime = [NSDate date];

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];

[dateFormatter setDateFormat:@"hh:mm dd/MM/yyyy"];

NSString *newlyFormattedDateString = [dateFormatter stringFromDate:dateAndtime];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM