NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init]autorelease];
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
[dateFormatter setDateFormat:@"dd/MM/yyyy hh:mmaaa"];
NSDate *date = [NSDate date];
NSString * s = [dateFormatter stringFromDate:date];
显示效果为:10/05/2010 03:49PM
下面附上几个格式:这个是从Cocoachina上来的。呵呵。
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, '99
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
下面是得到当前的年,月,日,时,分,秒。
NSDate *date = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *dd = [cal components:unitFlags fromDate:date];
int y = [dd year];
int m = [dd month];
int d = [dd day];
int h = [dd hour];
int min = [dd minute];
int s = [dd second];
例如:
NSString *startData = @"1374249600";
//NSString *startData = @"1374249600000";
NSTimeInterval nsTimeInterval = [startData integerValue];
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:nsTimeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatteralloc] init];
NSTimeZone* timeZone = [NSTimeZone localTimeZone];
NSLog(@"localTimeZone is %@",timeZone);
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
NSString *s = [dateFormatter stringFromDate:date];
NSLog(@"+++++++s:%@" ,s);
输出结果:
localTimeZone is Local Time Zone (Asia/Shanghai (CST (China)) offset 28800)
+++++++s:2013-07-20 00:00:00.000
//将日期字符串类型转化成日期类型
NSDateFormatter *dateF = [[NSDateFormatter alloc] init];
[dateF setDateStyle:NSDateFormatterFullStyle]; //this format will be according to your own.
NSDate *todayDate = [dateF dateFromString: @"5-MAY-2011 00:00:00 +0000"];//please note, this date format must match the NSDateFormatter Style, or else return null.
NSTimeInterval inter = [todayDate timeIntervalSince1970]; //return as double