我有一个以这种格式返回日期的网络服务:
2013-04-14
我如何弄清楚这对应的日期?
答案 0 :(得分:11)
此代码将获取您的字符串,将其转换为NSDate对象并提取当天的数字(14)和当天的名称(星期日)
NSString *myDateString = @"2013-04-14";
// Convert the string to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd";
NSDate *date = [dateFormatter dateFromString:myDateString];
// Extract the day number (14)
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date];
NSInteger day = [components day];
// Extract the day name (Sunday)
dateFormatter.dateFormat = @"EEEE";
NSString *dayName = [dateFormatter stringFromDate:date];
// Print
NSLog(@"Day: %d: Name: %@", day, dayName);
注意:此代码适用于ARC。如果是MRC,请在最后添加[dateFormatter release]。
答案 1 :(得分:6)
获得工作日的另一种方法可以是:
NSString *myDateString = @"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:myDateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
NSInteger weekday = [components weekday];
NSString *weekdayName = [dateFormatter weekdaySymbols][weekday - 1];
NSLog(@"%@ is a %@", myDateString, weekdayName);
答案 2 :(得分:3)
您可以使用此代码为我工作。
NSString *dateString = @"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:@"EEEE"];
NSLog(@"%@", [dateFormatter stringFromDate:dateFromString]);
答案 3 :(得分:0)
如果2013-04-14
存储在名为NSString
的{{1}}中,那么您可以执行此操作...
date
答案 4 :(得分:0)
let datFromat = DateFormatter()
datFormat.dateFormat = "EEEE"
let name = datFormat.string(from: Date())
奖金:如果您想设置自己的日期模板,而不是使用上面的Date()
:
let datFormat = DateFormatter()
datFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let thisDate = datFormat.date(from: "2016-10-13T18:00:00-0400")
然后在此之后调用第一个代码。