IOS格式规范

IOS格式规范

 

目录

  • 概述
  • 日期格式
  • NSDateFormatter格式说明

 

概述

 

日期格式

声明时间格式:NSDateFormatter *date_formatter = [[NSDateFormatter alloc] init];

设置时间格式:[date_formatter setDateFormat:@"yyyy年MM月dd日HH时mm分ss秒"];

设值locale:[date_formatter setLocale:[[NSLocale alloc] initWithLocaleIndentifier:@"en_US"]]或者[date_formatter setLocale:[NSLocale currentLocale]];

获得日期

获得当前日期:NSDate *current_date = [NSDate date];

从字符串中获得日期:NSDate *custom_date = [date_formatter stringFromDate:@"20140905133212"];

把获得日期按照相应格式转换为字符串:NSString *str = [date_formatter stringFromDate:current_date];

 

NSDateFormatter格式说明

G:公元时代,例如AD公元

yy:年的后2位

yyyy:完整年

MM:月,显示为1-12

MMM:月,显示为英文月份简写,如Jan

MMMM:月,显示为英文月份全称,如January

dd:日,2位数表示,如2

d:日,1-2位显示,如2

EEE:简写星期几,如Sun

EEEE:全写星期几,如Sunday

aa:上下午,AM/PM

H:时,24小时制,0-23

K:时,12小时制,0-11

m:分,1-2位

mm:分,2位

s:秒,1-2位

ss:秒,2位

S:毫秒

注意:M和m是代表不同的,M代表月份,m代表分

常用日期结构

yyyy-MM-dd HH:mm:ss.sss

yyyy_MM-dd HH:mm:ss

yyyy-MM-dd

MM dd yyyy

 

自定义显示的星期格式 

使用NSDateFormatter转换日期时,得到的英文字母的星期几只能是这样,如Sun, Mon, etc.

 

如果想得到大写字母的星期几,可以这样:

 

NSArray*weekdayAry = [NSArray arrayWithObjects:@"SUN", @"MON", @"TUE",@"WED", @"THU", @"FRI", @"SAT", nil];

 

dateFormatter = [[NSDateFormatter alloc] init];

 

[dateFormatter setDateFormat:NSLocalizedString(@"YYYY.MM.dd.eee",nil)];

 

//此处更改显示的大写字母的星期几
[dateFormattersetShortWeekdaySymbols:weekdayAry];

 

[dateFormatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"] ]];

 

NString *str= [dateFormatter stringFromDate:[NSDate date]];

  

计算距离某一天还有多少时间

 

NSDate* toDate = [ [ NSDate alloc]initWithString:@"2012-9-29 0:0:00 +0600" ];

 

NSDate* startDate = [ [ NSDatealloc] init ];

 

NSCalendar* chineseClendar = [ [ NSCalendar alloc ]initWithCalendarIdentifier:NSGregorianCalendar ];

 

NSUInteger unitFlags =

 

NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit |NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;

 

NSDateComponents *cps = [chineseClendar components:unitFlagsfromDate:startDate toDate:toDate options:0];

 

NSInteger diffHour = [cps hour];

 

NSInteger diffMin = [cpsminute];

 

NSInteger diffSec = [cps second];

 

NSInteger diffDay = [cps day];

 

NSInteger diffMon = [cps month];

 

NSInteger diffYear = [cps year];

 

NSLog( @" From Now to %@, diff: Years:%d Months: %d, Days; %d, Hours: %d, Mins:%d,sec:%d",

 

[toDate description], diffYear, diffMon, diffDay, diffHour,diffMin,diffSec );

 

原文地址:https://www.cnblogs.com/IOS-Developer/p/4118271.html