문제

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.

도움이 되었습니까?

해결책

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];

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top