Iphone 如何将日期初始化为NSdate?
例如,我想以Iphone 如何将日期初始化为NSdate?,iphone,Iphone,例如,我想以mm/dd/yyyy的格式给出12/11/2005。我可以直接将12/11/2005初始化为NSDate吗?有什么帮助吗 当我声明它为 NSDate *then = [NSDate dateWithNaturalLanguageString:02/11/2009 locale:nil]; 使用+(id)dateWithNaturalLanguageString:(NSString*)string :您需要做的是: NSDateFormatter *mmddccyy = [[NSD
mm/dd/yyyy
的格式给出12/11/2005
。我可以直接将12/11/2005
初始化为NSDate
吗?有什么帮助吗
当我声明它为
NSDate *then = [NSDate dateWithNaturalLanguageString:02/11/2009 locale:nil];
使用+(id)dateWithNaturalLanguageString:(NSString*)string
:您需要做的是:
NSDateFormatter *mmddccyy = [[NSDateFormatter alloc] init];
mmddccyy.timeStyle = NSDateFormatterNoStyle;
mmddccyy.dateFormat = @"MM/dd/yyyy";
NSDate *d = [mmddccyy dateFromString:@"12/11/2005"];
NSLog(@"%@", d);
另一个解决方案可能是使用NSCalendar和NSDateComponents,因为不推荐使用+dateWithNaturalLanguageString: 例如,您希望将NSDate初始化为2001年8月15日。这是适用于您的代码:
NSCalendar *g = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.year = 2001;
comps.month = 8;
comps.day = 15;
NSDate *myDate = [g dateFromComponents:comps];
或者另一种方式是:
let earliestDate = calendar.dateWithEra(1, year: 2012, month: 1, day: 1, hour: 0, minute: 0, second: 0, nanosecond: 0)
要将最早的日期NSDate设置为2012年1月1日它会发出警告…当我声明为NSDate*时会崩溃…然后=[NSDate DATE WITH NATURALLANGUAGESTRING:02/11/2009地区:nil];您需要传递一个NSString。NSDate*then=[NSDate DATE WITH NATURALLANUAGESTRING:@“02/11/2009”地区:nil];此方法仅适用于Mac OS X v10.0及更高版本,在iOS中不可用
02/11/2009
不是NSString<代码>@“02/11/2009”为。