本文共 2220 字,大约阅读时间需要 7 分钟。
获取当前日期时间的代码如下:
NSDate *dateToDay = [NSDate date]; NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"yyyy-MM-DD HH:mm:ss"]; NSLocale *local = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; [df setLocale:local]; NSString *myDataString = @"2009-09-15 18:30:00";
从字符串生成日期对象的代码如下:
NSDate *myData = [df dateFromString:myDataString];
日期比较的代码如下:
switch ([dateToDay compare:myData]) { case NSOrderedSame: NSLog(@"These dates are the same!"); break; case NSOrderedAscending: NSLog(@"dateToDay is earlier than myDate!"); break; case NSOrderedDescending: NSLog(@"mydate is earlier than dateToDay"); break; default: NSLog(@"Bad times. Invalid enum value returned."); break; }
注意:掌握NSDate和NSString相互之间的转换。
完整代码如下:
#importint main(int argc, const char * argv[]){ NSDate *dateToDay = [NSDate date]; NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"yyyy-MM-DD HH:mm:ss"]; NSLocale *local = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; [df setLocale:local]; NSString *myDataString = @"2009-09-15 18:30:00"; NSDate *myData = [df dateFromString:myDataString]; switch ([dateToDay compare:myData]) { case NSOrderedSame: NSLog(@"These dates are the same!"); break; case NSOrderedAscending: NSLog(@"dateToDay is earlier than myDate!"); break; case NSOrderedDescending: NSLog(@"mydate is earlier than dateToDay"); break; default: NSLog(@"Bad times. Invalid enum value returned."); break; } return 0;}
NSData转换为NSString的代码如下:
NSMutableData *data; NSString *tmpdata = [[NSString alloc] initWithString:data encoding:NSASCIIStringEncoding]; NSLog(@"[***] DATA:%@" , tmpdata); [tmpdata release];
NSString转换为NSData的代码如下:
NSString *str = @"teststring"; NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
本文转自夏雪冬日博客园博客,原文链接:http://www.cnblogs.com/heyonggang/p/3475024.html,如需转载请自行联系原作者