xcode项目中的时区


    NSCalendar *calendar = [NSCalendar currentCalendar];
                [calendar setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
                NSDateComponents *comps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:ExamTime];
                 NSDate *newDate = [calendar dateFromComponents:comps];
 NSDateFormatter *timeformater = [[NSDateFormatter alloc] init];
            [timeformater setLocale:[NSLocale currentLocale]];
            [timeformater setDateFormat:@"EEEE-dd-MMMM-yyyy HH:mm a"];
                NSString *strSelectedDate= [timeformater stringFromDate:newDate];

我写这段代码,我想改变时区的时间问题没有解决,请帮助我,谢谢

您不需要首先将日期转换为NSDateComponents。只需创建NSDateFormatter,设置格式和时区,并将日期转换为字符串。要设置时区为GMT(+0000),创建如下:

NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
所以整个代码看起来像这样:
NSDateFormatter *timeformater = [[NSDateFormatter alloc] init];
[timeformater setLocale:[NSLocale currentLocale]];
NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
[timeformater setTimeZone:timeZone];
[timeformater setDateFormat:@"EEEE-dd-MMMM-yyyy HH:mm a"];
NSString *strSelectedDate= [timeformater stringFromDate:ExamTime];

我认为您要设置的时区名称有问题。您可以通过以下命令获取所有时区:

NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];

则可以将时区设置为:

NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CDT"]];
NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init];
[timeZoneComps setHour:16];
//specify whatever day, month, and year is appropriate
NSDate *date=[gregorian dateFromComponents:timeZoneComps];

您可以在以下网站获得更多详细信息:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtTimeZones.html

相关内容

  • 没有找到相关文章

最新更新