我在对象" start_time"(2000-12-11T00:00:00 + 0000)中有日期,但我需要将日期和时间分别打印到文本字段。但是,当我尝试使用此代码时,我在控制台上获得了空值
__block NSDictionary *events = [[e.response objectForKey:@"events"] objectAtIndex:0];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// NSDate *dates = [events objectForKey:@"start_time"];
// NSDate *localDate = [NSDate date];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]init] init];
dateFormatter.dateFormat = @"MMMM dd yyyy";
NSString *dateString = [dateFormatter stringFromDate: [events objectForKey:@"start_time"]];
NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc] init] init];
timeFormatter.dateFormat = @"HH:mm:ss ZZZZ";
NSString *timeString = [timeFormatter stringFromDate: [events objectForKey:@"start_time"]];
NSLog(@"This is time------------------------------: %@",dateString); // null returns
// 这就是我如何将日期存储到" start_time"通过textfields
块引用
NSString *datestring = self.date.text;
NSString *timestring = self.time.text;
NSString *combined = [NSString stringWithFormat:@"%@ %@", datestring, timestring];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:05.30]];
[dateFormat setDateFormat:@"MM dd yyyy HH:mm a"];
NSDate *date = [dateFormat dateFromString:combined];
NSDictionary *data = @{
@"start_time":[NSString stringWithFormat:@"%@",date]};
答案 0 :(得分:1)
我认为那变为null
因为您从不同格式的事件中即将到来的日期并且您首先设置格式是不同的。
dateFormatter.dateFormat = @"MMMM dd yyyy";
必须:
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";
您必须设置第一个当前日期格式,然后您可以将其更改为您想要的日期。
答案 1 :(得分:0)
您设置的日期格式不正确
尝试以下操作,这将有效
//"myDate" variable is an example string, you can change it with "[events objectForKey:@"start_time"]"
NSString *myDate = @"2000-12-11T00:00:00 +0000";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]init] init];
dateFormatter.dateFormat = @"yyyy-dd-mm'T'HH:mm:ss Z";
NSDate *myDateObject = [dateFormatter dateFromString:myDate]; //Now you have the date object that return the correct value
//FOR date
[dateFormatter setDateFormat:@"yyyy-dd-mm"];
NSString *OnlyDate = [dateFormatter stringFromDate:myDateObject];
//For Time
[dateFormatter setDateFormat:@"HH:mm:ss Z"];
NSString *OnlyTime = [dateFormatter stringFromDate:myDateObject];
NSLog(@"Date is %@ and Time is %@",OnlyDate,OnlyTime);
<强>更新强>
在您的情况下,如果[events objectForKey:@“start_time”]是NSDATE对象,请尝试以下
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]init] init];
dateFormatter.dateFormat = @"yyyy-dd-mm'T'HH:mm:ss Z";
NSDate *myDateObject = [dateFormatter dateFromString:[events objectForKey:@"start_time"]]; //Now you have the date object that return the correct value
//FOR date
[dateFormatter setDateFormat:@"yyyy-dd-mm"];
NSString *OnlyDate = [dateFormatter stringFromDate:myDateObject];
//For Time
[dateFormatter setDateFormat:@"HH:mm:ss Z"];
NSString *OnlyTime = [dateFormatter stringFromDate:myDateObject];
NSLog(@"Date is %@ and Time is %@",OnlyDate,OnlyTime);
希望这有帮助。