获取当前日期时间的代码如下:
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相互之间的转换。
完整代码如下:
#import <Foundation/Foundation.h> int 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];
微信公众号:
猿人谷
如果您认为阅读这篇博客让您有些收获,不妨点击一下右下角的【推荐】
如果您希望与我交流互动,欢迎关注微信公众号
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。