NSDate 常用

使用NSTimer实现倒计时

- (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:2010]; 
[shibo setMonth:5]; 
[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]; 
lab.text = [NSString stringWithFormat:@"%d年%d月%d日%d时%d分%d秒",[d year],[d month], [d day], [d hour], [d minute], [d second]]; 
}

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

在 NSDate中获得时间信息,年、月、星期、日、时、分、秒和毫秒:

注:第一种方法不能获取毫秒的信息,最后利用第二种方法实现了获取毫秒的信息



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];

 

NSDataToNSString方法:

-(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 = [[NSCalendaralloc]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(@"%02i,%02i,%02.0f,",currentDate.hour,currentDate.minute,currentDate.second);

 http://stackoverflow.com/questions/1338557/nsdate-datewithnaturallanguagestring-on-iphone

One way to do this is with NSCalendar and NSDateComponents.

To get today at 23:59:59:

NSDate*now =[NSDate date];
NSCalendar*calendar =[NSCalendar currentCalendar];


NSDateComponents*comps =[calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|  NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit 
                                                                          fromDate:date];


[comps setHour:23];
[comps setMinute:59];
[comps setSecond:59];


NSDate*today =[calendar dateFromComponents:comps];

To get tomorrow at 23:59:59:

NSDate *now = [NSDate dateWithTimeIntervalSinceNow:24 * 60 * 60]; // 24h from now
NSCalendar *calendar = [NSCalendar currentCalendar];


NSDateComponents *comps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit 
                                                                          fromDate:date];


[comps setHour:23];
[comps setMinute:59];
[comps setSecond:59];


NSDate *tomorrow = [calendar dateFromComponents:comps];

You can get now and now+24 hours with:

static const unsigned long seconds_per_day = 60 * 60 * 24;
NSDate* today = [NSDate date]; // set for today
NSDate* tomorrow = [today addTimeInterval:seconds_per_day];

In order to get midnight for the given day, it's important to remember that  NSDate*  is toll-free bridged to  CFDateRef , which provides some additional APIs you'll want to use. In particular, you can convert an  NSDate  to a  CFAbsoluteTime  with  CFDateGetAbsoluteTime :
CFAbsoluteTime abstime = CFDateGetAbsoluteTime(reinterpret_cast(myNSDate));
long long      inttime = static_cast(abstime);


inttime = (inttime / seconds_per_day) * seconds_per_day; // clips the time to midnight


NSDate* myNSDateAtMidnight = reinterpret_cast(CFDateCreate(NULL,
                                                       static_cast(inttime)));

iphone获取1970年以来的毫秒数

Object-C获取自1970年以来的毫秒数

NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
// 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型

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

这里要使用ios有关的日期时间api:

  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];

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:date];

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];



iOS-NSDateFormatter 格式说明(转载)

格式化参数如下:
    G: 公元时代,例如AD公元
    yy: 年的后2位
    yyyy: 完整年
    MM: 月,显示为1-12
    MMM: 月,显示为英文月份简写,如 Jan
    MMMM: 月,显示为英文月份全称,如 Janualy
    dd: 日,2位数表示,如02
    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: 毫秒

常用日期结构:
yyyy-MM-dd HH:mm:ss.SSS
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd
MM dd yyyy

NSDate获取当前时区的时间

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

NSDate *date = [NSDate date];

NSTimeZone *zone = [NSTimeZone systemTimeZone];

NSInteger interval = [zone secondsFromGMTForDate: date];

NSDate *localeDate = [date  dateByAddingTimeInterval: interval];  

NSLog(@"%@", localeDate);

setCalendarFormat 用法
摘要: - (void)setCalendarFormat:(NSString *)formatThis method sets the default calendar format for the receiver. A calendar format is a string formatted with date-conversion specifiers, as given inTable 3.2.Table 3.2. Possible Tokens in the Calendar Format StringSymbolMeaning%yYear without century (00-99) 阅读全文

posted @ 2012-02-05 17:49 pengyingh 阅读(21) | 评论 (0)  编

你可能感兴趣的:(iOS)