iOS NSDate

充昌勋
2023-12-01

使用NSTime实现倒计时功能


- (void)timerFireMethod:(NSTimer*)theTimer


{


    //NSDateFormatter *dateformatter = [[[NSDateFormatter alloc]init] autorelease];//定义NSDateFormatter用来显示格式


    //[dateformatter setDateFormat:@"yyyy MM dd hh mm ss"];//设定格式 


    NSCalendar *cal = [NSCalendar currentCalendar];//定义一个NSCalendar对象


    NSDateComponents *shibo = [[NSDateComponents alloc] init];//初始化目标时间(好像是世博会的日期) 


    [shibo setYear:2012];


    [shibo setMonth:6];


    [shibo setDay:1];


    [shibo setHour:8];


    [shibo setMinute:0];


    [shibo setSecond:0];


   


    NSDate *todate = [cal dateFromComponents:shibo];//把目标时间装载入date


    [shibo release];


    // NSString *ssss = [dateformatter stringFromDate:dd];


    // NSLog([NSString stringWithFormat:@"shibo shi:%@",ssss]);


   


    NSDate *today = [NSDate date];//得到当前时间 


    // NSString *sss = [dateformatter stringFromDate:today];


    // NSLog([NSString stringWithFormat:@"xianzai shi:%@",sss]);


    //用来得到具体的时差 


    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;


    NSDateComponents *d = [cal components:unitFlags fromDate:today toDate:todate options:0];


    NSString *result = [NSString stringWithFormat:@"%d年%d月%d日%d时%d分%d秒",[d year],[d month], [d day], [d hour], [d minute], [d second]];


    NSLog(@"%@",result);


}


 在 初始化方法中调用[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];即可





 NSData年、月、星期、日、时、分、秒和毫秒获取及NSDataToNSString方法


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


    NSDate *now;


    NSDateComponents *comps = [[NSDateComponents alloc] init];


    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |


    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;


    now=[NSDate date];


    comps = [calendar components:unitFlags fromDate:now];


    int year=[comps year];


    int week = [comps weekday];  


    int month = [comps month];


    int day = [comps day];


    int hour = [comps hour];


    int min = [comps minute];


    int sec = [comps second];


    NSLog(@"%d-%d-%d %d:%d:%d",year,month,day,hour,min,sec);




    NSMutableDictionary *dictionary =[NSMutableDictionary dictionaryWithCapacity:2];


    [dictionary setValue:path forKey:@"photo_path"];


    NSDate *date = [NSDate date];


    NSTimeZone *zone = [NSTimeZone systemTimeZone];


    NSInteger interval = [zone secondsFromGMTForDate: date];


    NSDate *localeDate = [date  dateByAddingTimeInterval: interval]; 


    NSLog(@"%@", localeDate);


    NSLog(@"%@",[self NSDateToNSTring:[NSDate date]]);//返回的是GTM时间


    NSLog(@"%@",[self NSDateToNSTring:localeDate]);//返回的是北京时间


-(NSString *)NSDateToNSTring:(NSDate *)nsDate


{


    //NSString *string = [nsDate descriptionWithCalendarFormat:@"%Y/%m/%d %H:%M:%S" timeZone:nil locale:nil];              此方法为是有API如果要上传APP不要使用


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


    //  [fmt setDateFormat:@"hh:mm:ss:SSS"];


    [fmt setDateFormat:@"yyyy/MM/dd hh:mm:ss:SSS"]; 


    NSString *string=[fmt stringFromDate:nsDate]; 


    return string; 


}




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


    NSDate *date = [NSDate date];


    NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:date];


    [gregorian release];


    NSLog(@"%02i:%02i:%02i",[dateComponents hour],[dateComponents minute],[dateComponents second]);




    CFGregorianDate currentDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem());


    NSLog(@"%04ld-%02i-%02i %02i:%02i:%02.0f", currentDate.year,currentDate.month,currentDate.day,currentDate.hour,currentDate.minute,currentDate.second);




 iphone获取1970年以来的毫秒数


    // NSTimeInterval返回的是double类型,输出会显示为10位整数加小数点加一些其他值


    // 如果想转成int型,必须转成long long型才够大。


    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];


    long long dTime = [[NSNumber numberWithDouble:time] longLongValue]; // 将double转为long long型


     NSString *curTime = [NSString stringWithFormat:@"%llu",dTime]; // 输出long long型


     NSLog(@"%@",curTime);






 iOS 应用里获取日期间隔的方法


    //NSDate,类似java里面的Date对象,是对从1970-1-1毫秒数的封装,可记录时间;


    //NSDateFormatter,类似java中的DateFormat相关的api,用于日期对象的格式化或者字符串解析为日期对象。


    //首先,创建一个日期格式化对象:


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


    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];


    //然后,创建了两个日期对象:


    NSDate *date1=[dateFormatter dateFromString:@"2010-3-3 11:00"];


    NSDate *date2=[dateFormatter dateFromString:@"2010-3-4 12:00"];


    //创建日期对象,是通过字符串解析的。


    //然后取两个日期对象的时间间隔:


    NSTimeInterval time=[date2 timeIntervalSinceDate:date1];


    //这里的NSTimeInterval 并不是对象,是基本型,其实是double类型,是由c定义的:


    typedef double NSTimeInterval;


    //再然后,把间隔的秒数折算成天数和小时数:


    int days=((int)time)/(3600*24);


    int hours=((int)time)%(3600*24)/3600;


    NSString *dateContent=[[NSString alloc] initWithFormat:@"%i天%i小时",days,hours];


    NSLog(@"%@",dateContent);




 ios中NSString与NSDate互转


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


    NSTimeZone *timeZone = [NSTimeZone localTimeZone];


   


    [formatter setTimeZone:timeZone];


    [formatter setDateFormat : @"M/d/yyyy h:m a"];


   


    NSString *stringTime = @"12/5/2011 3:4 am";


    NSDate *dateTime = [formatter dateFromString:stringTime];


    NSLog(@"%@", dateTime);//打印2011-12-04 19:04:00 +0000,这里+0000表示时区


    NSDate *dateNow = [NSDate date];


   


    NSLog(@"%@", dateNow);//打印2011-08-17 08:26:57 +0000,这里+0000表示时区


    


    [formatter setDateFormat : @"yyyy年M月d日H点m分"];


   


    NSLog(@"%@", [formatter stringFromDate:dateNow]);//打印2011年8月17日16点26分




 NSDateFormatter setDateFormat 自定义日期/时间格式


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


    //  NSString *tzStr = [[date description] substringFromIndex:20];


    //  NSLog(@"\ndate\t:[%@]\ntime zone\t:[%@]", [date description], tzStr);


    //  [dateFormatter setTimeZone:tzStr];


    [dateFormatter setDateFormat:@"MM d','h:m a"];


    //  [dateFormatter setDateStyle:kCFDateFormatterMediumStyle];


    //  [dateFormatter setTimeStyle:kCFDateFormatterShortStyle];


    //  [NSLog(@"Local time zone [%@'", [dateFormatter timeZone]);


    NSString *dateStr = [dateFormatter stringFromDate:[NSDate date]];


    NSLog(@"==========%@",dateStr);




 NSDateFormatter




格式化日期字符串,copy一份常用参数:

a: AM/PM (上午/下午)

A: 0~86399999 (一天的第A微秒)

c/cc: 1~7 (一周的第一天, 周天为1)

ccc: Sun/Mon/Tue/Wed/Thu/Fri/Sat (星期几简写)

cccc: Sunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday (星期几全拼)

d: 1~31 (月份的第几天, 0)

D: 1~366 (年份的第几天,0)

e: 1~7 (一周的第几天, 0)

E~EEE: Sun/Mon/Tue/Wed/Thu/Fri/Sat (星期几简写)

EEEE: Sunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday (星期几全拼)

F: 1~5 (每月的第几周, 一周的第一天为周一)

g: Julian Day Number (number of days since 4713 BC January 1) 未知

G~GGG: BC/AD (Era Designator Abbreviated) 未知

GGGG: Before Christ/Anno Domini 未知

h: 1~12 (0 padded Hour (12hr)) 0的时, 12小时制

H: 0~23 (0 padded Hour (24hr))  0的时, 24小时制

k: 1~24 (0 padded Hour (24hr) 0的时, 24小时制

K: 0~11 (0 padded Hour (12hr)) 0的时, 12小时制

L/LL: 1~12 (0 padded Month)  第几月

LLL: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec 月份简写

LLLL: January/February/March/April/May/June/July/August/September/October/November/December 月份全称

m: 0~59 (0 padded Minute) 分钟

M/MM: 1~12 (0 padded Month) 第几月

MMM: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec

MMMM: January/February/March/April/May/June/July/August/September/October/November/December

q/qq: 1~4 (0 padded Quarter) 第几季度

qqq: Q1/Q2/Q3/Q4 季度简写

qqqq: 1st quarter/2nd quarter/3rd quarter/4th quarter 季度全拼

Q/QQ: 1~4 (0 padded Quarter) 同小写

QQQ: Q1/Q2/Q3/Q4 同小写

QQQQ: 1st quarter/2nd quarter/3rd quarter/4th quarter 同小写

s: 0~59 (0 padded Second) 秒数

S: (rounded Sub-Second) 未知

u: (0 padded Year) 未知

v~vvv: (General GMT Timezone Abbreviation) 常规GMT时区的编写

vvvv: (General GMT Timezone Name) 常规GMT时区的名称

w: 1~53 (0 padded Week of Year, 1st day of week = Sunday, NB: 1st week of year starts from the last Sunday of last year) 一年的第几周, 一周的开始为周日,第一周从去年的最后一个周日起算

W: 1~5 (0 padded Week of Month, 1st day of week = Sunday) 一个月的第几周

y/yyyy: (Full Year) 完整的年份

yy/yyy: (2 Digits Year)  2个数字的年份

Y/YYYY: (Full Year, starting from the Sunday of the 1st week of year) 这个年份未知干嘛用的

YY/YYY: (2 Digits Year, starting from the Sunday of the 1st week of year) 这个年份未知干嘛用的

z~zzz: (Specific GMT Timezone Abbreviation) 指定GMT时区的编写

zzzz: (Specific GMT Timezone Name) Z: +0000 (RFC 822 Timezone) 指定GMT时区的名称

 

实例:

http://blog.sina.com.cn/s/blog_60b45f230100i0r9.html

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

 

 

 

下面是得到当前的年,月,日,时,分,秒。

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 m = [dd minute];

int s = [dd second];



NSDate获取当前时区的时间




[NSDate date]获取的是GMT时间,要想获得某个时区的时间,以下代码可以解决这个问题

NSDate *date = [NSDate date];

NSTimeZone *zone = [NSTimeZone systemTimeZone];

NSInteger interval = [zone secondsFromGMTForDate: date];

NSDate *localeDate = [date  dateByAddingTimeInterval: interval];  

NSLog(@"%@", localeDate);

 

更多 0

 类似资料:

相关阅读

相关文章

相关问答