Question

iOS Programming: I just want to let iOS7 get the "America/Chicago" current date and time. I searched a lot on Internet, but there are a lot of different solutions. I tried several solutions, but they do not work.

Was it helpful?

Solution

You can use the NSCalendar and NSTimezone classes. The following code segment demonstrates retrieving the current hour and minute. Extending it to retrieve other date components is straight-forward -

long hour;
long minute;
NSCalendar *cal=[NSCalendar currentCalendar];
NSDate *now=[NSDate date];
NSTimeZone *tz=[NSTimeZone timeZoneWithName:@"America/Chicago"];

[cal setTimeZone:tz];
NSDateComponents *comp=[cal components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:now];
hour=[comp hour];
min=[comp minute];

OTHER TIPS

You can use this method,

- (NSDate *) getCountryDateWithTimeZone:(NSString *)zone
{

    NSDate *now = [NSDate date];
    NSTimeZone *szone = [NSTimeZone timeZoneWithName:zone];

    NSInteger sourceGMTOffset = [szone secondsFromGMTForDate:now];
    NSTimeInterval interval = sourceGMTOffset;
    NSDate *destinationDate = [NSDate dateWithTimeInterval:interval sinceDate:now];

    return destinationDate;
}

And,

[self getCountryDateWithTimeZone:@"America/Chicago"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSString *firstDate = @"2014-06-05 12:55:00";

NSDate *date=[dateFormatter dateFromString:firstDate];

NSDate *currentDate = [NSDate date];

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:date toDate:currentDate options:0];

NSLog(@"The difference between from date and to date is %d days and %d hours and %d minute and %d second",components.day,components.hour,components.minute,components.second);

Output:

DateBookApp[1179:70b] The difference between from date and to date is 0 days and 22 hours and 57 minute and 12 Second

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top