Converting a NSString into NSDate

浪尽此生 提交于 2019-12-02 14:10:08

问题


I have date string: Monday, October 11, 2010. How can I create a NSDate object out of it and then get different components like day, month, date, year from it. Please note that format/locale of this string may change at runtime.


回答1:


another possibility:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:date];
NSInteger year = [components year];
...



回答2:


Use an NSDateFormatter to create the NSDate, then you can access its components through NSDate properties (you'll need to adjust the format string below):

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];

if(NSDate *myDate = [df dateFromString:string]) {
    //Do something with myDate
}


来源:https://stackoverflow.com/questions/3910920/converting-a-nsstring-into-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!