Reputation: 7978
I have a strange hour computation. Take this log:
NSLog(@"Load Data in event %@ %d",currentDate,[currentDate hour]);
In the logs:
Load Data in event 2013-09-18 06:30:00 +0000 2147483647
where currentDate is an NSDate an the category of NSDate is:
- (int)hour
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:self];
[components setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSInteger hour = [components hour];
return hour;
}
Upvotes: 3
Views: 213
Reputation: 5186
Try use below code:
NSString *strCurrentDate;
NSString *strNewDate;
NSDate *date = [NSDate date];
NSDateFormatter *df =[[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd HH:mm a"];
strCurrentDate = [df stringFromDate:date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
NSDate *newDate= [calendar dateByAddingComponents:components toDate:date options:0];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];
strNewDate = [df stringFromDate:newDate];
NSLog(@"New Date and Time: %@",strNewDate)
Upvotes: -1
Reputation: 130210
Remove
[components setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
Note that NSDateComponents
don't perform any time-zone calculations so setting a time zone on them before querying a value has no meaning.
Upvotes: 2
Reputation: 800
NSDate *today = [NSDate date];
NSLog(@"Today's date: %@",today);
unsigned hourAndMinuteFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSDateComponents* travelDateTimeComponents = [calendar components:hourAndMinuteFlags fromDate:today];
NSString* hours = [NSString stringWithFormat:@"%02i", [travelDateTimeComponents hour]];
NSString* minutes = [NSString stringWithFormat:@"%02i", [travelDateTimeComponents minute]];
NSLog(@"Hours: %@",hours);
NSLog(@"Minutes: %@",minutes);
Upvotes: 3