本文主要是介绍NSDate_前进的火车_新浪博客,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
NSDae
获取世界标准时间
NSDate *date = [NSDate date];
获取本地时间
NSDate *date = [NSDate date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:date];
NSDate *localDate = [date dateByAddingTimeInterval:interval];
获取比当前时间快30秒的世界标准时间(类方法)
NSDate *date2 = [NSDate dateWithTimeIntervalSinceNow:30];
获取自1970年1月1日0时到现在的总秒数(输出结果为double类型/因为单位是秒)
NSTimeInterval seconds = [date timeIntervalSince1970];
.获取两个指定时间之间的总秒数
NSDate *time1 = [NSDate dateWithTimeIntervalSinceNow:-60 * 60 * 24];
NSDate *time2 = [NSDate dateWithTimeIntervalSinceNow:60 * 60 * 24];
NSTimeInterval seconds2 = [time1 timeIntervalSinceDate:time2]; (time1-time2)
对比两个时间谁更早
NSDate *earlierDate = [time1 earlierDate:time2];
谁更晚
NSDate *laterDate = [time1 laterDate:time2];
对比两个时间是否相同
if ([time1 isEqualToDate:time2] == YES)
NSLog(@"两个时间相同");
else
NSLog(@"两个时间不同");
指定时间的输出格式
NSDateFormatter *f = [[NSDateFormatter alloc] init];
f.dateFormat = @"yyyy年MM月dd日 hh:mm:ss";
NSString *strDate = [f stringFromDate:date];
//获取本地时间
NSDate *nowdate = [[NSDate alloc] init];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/BeiJing"];
[formatter setTimeZone:timeZone];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd-HH-mm-ss"];
NSString *timeStr = [formatter stringFromDate:nowdate];
NSArray *time = [timeStr componentsSeparatedByString:@"-"];
//时间加减
NSString *dateString = _headerLabel.text;//NSString类型转成NSDate类型
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [formatter dateFromString:dateString];
NSInteger year = 0;//NSDate类型再进行日期的加减处理
NSInteger month = 0;
NSInteger day;
if (sender.tag == 1) {
day = -1;
}else{
day = 1;
}
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = nil;
comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
NSDateComponents *adcomps = [[NSDateComponents alloc] init];
[adcomps setYear:year];
[adcomps setMonth:month];
[adcomps setDay:day];
NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:date options:0];
NSString *text = [formatter stringFromDate:newdate];
这篇关于NSDate_前进的火车_新浪博客的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!