我有一个字符串格式的日期
2012-11-09T00:00:00
我需要将它作为day=Fri Date-09
.
我尝试了很多方法但是日期打印为空。有人可以帮我吗?我想在我创建的自定义日历中显示它。
我有一个字符串格式的日期
2012-11-09T00:00:00
我需要将它作为day=Fri Date-09
.
我尝试了很多方法但是日期打印为空。有人可以帮我吗?我想在我创建的自定义日历中显示它。
使用以下代码获取所需的值
NSString *dateStr = @"2012-11-09T00:00:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"GMT"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString: dateStr];
NSLog(@"Date : %@", date);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents =
[calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];
NSInteger weekday = [dateComponents weekday];
NSInteger monthdate = [dateComponents day];
NSLog(@"Weekday : %d Month date %d ", weekday, monthdate);
我们将工作日获取为从 1 到 7 的整数。您必须相应地转换工作日。
试试这个代码:
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"dd"];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int weekday = [comps weekday];
NSArray *arr=[NSArray arrayWithObjects:@"sun",@"mon",@"tue",@"wed",@"thu",@"fri",@"sat", nil];
NSLog(@"day=%@ Date-%@",[arr objectAtIndex:weekday-1],[dateFormatter stringFromDate:[NSDate date]]);
当前日期的结果
day=mon Date-29
试试这个方法...
-(NSString *)convertStringToDate:(NSString *) strdate {
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString: strdate];
dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"EEE, dd MM yyyy HH:mm:ss"];
NSString *convertedString = [dateFormatter stringFromDate:date];
NSLog(@"Converted String : %@",convertedString);
return convertedString;
}