ios NSDate 没有返回我的本地时区/设备的默认时区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4547379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:23:54  来源:igfitidea点击:

NSDate is not returning my local Time zone /default time zone of device

iphoneios

提问by user556126

My local and default time zone is GMT +5 but when I get date and time by NSDate it return me GMT date and time.

我的本地和默认时区是 GMT +5,但是当我通过 NSDate 获取日期和时间时,它会返回 GMT 日期和时间。

For example the code and output from my code while testing on device is as, [device time zone Islamabad GMT +5]

例如,我的代码在设备上测试时的代码和输出为,[设备时区伊斯兰堡 GMT +5]

 NSTimeZone *lo = [NSTimeZone localTimeZone];
 NSLog(@" - current  local timezone  is  %@",lo); // GMT +5

2010-12-28 20:56:11.785 Done[484:307]  - current  local timezone  is  Local Time Zone (Asia/Karachi (GMT+05:00) offset 18000)

 NSTimeZone *df = [NSTimeZone defaultTimeZone];
 NSLog(@" - current  default timezone  is  %@",df); // GMT +5

2010-12-28 20:56:11.790 Done[484:307]  - current  default timezone  is  Asia/Karachi (GMT+05:00) offset 18000

but

 NSDate *cDate = [NSDate date];
 NSLog(@"current date by NSDate %@",cDate); //but NSDate show GMT
2010-12-28 20:56:11.794 Done[484:307] current date by NSDate 2010-12-28 15:56:11 GMT


 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";
 //// NSTimeZone *gmt = [NSTimeZone ]
 NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT+05:00"];
 [dateFormatter setTimeZone:gmt];

 NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
 NSLog(@" date string object  %@" ,timeStamp);   // string From Date is GMT +5
2010-12-28 20:56:11.802 Done[484:307]  date string object  2010-12-28T20:56


 NSDate *datef = [dateFormatter dateFromString:timeStamp]; 
 NSLog(@" date object %@" ,datef);  // the date form above string gives again GMT
2010-12-28 20:56:11.809 Done[484:307]  **date object 2010-12-28 15:56:00 GMT**

Why is NSDate not giving local current time? Please help...

为什么 NSDate 没有给出本地当前时间?请帮忙...

回答by Eliseo Chavez Jr.

Try this...

尝试这个...

NSDate* sourceDate = [NSDate date];

NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];

This help respond to the current system timezone.

这有助于响应当前系统时区。

回答by malhal

Forget NSDateFormatter - it's way too complicated, instead try this magic:

忘记 NSDateFormatter - 它太复杂了,试试这个魔法:

NSLog(@"Date with local timezone is: %@",
[date descriptionWithLocale:NSLocale.systemLocale]);

回答by Kendall Helmstetter Gelner

NSDate is a "raw" date. That's why it is in GMT. It's up to the code to use NSDateFormatter (as you have done) to output the date to a value that makes sense for the user.

NSDate 是“原始”日期。这就是为什么它在格林威治标准时间。由代码使用 NSDateFormatter(正如您所做的那样)将日期输出为对用户有意义的值。

In some rare cases you might need to display an NSDate not using the users time zone (like if you want to display a time in New York time no matter where the user is). Then, you set the time zone on the date formatter to a specific value (again, as you have done).

在极少数情况下,您可能需要不使用用户时区来显示 NSDate(例如,无论用户身在何处,您都想以纽约时间显示时间)。然后,您将日期格式化程序上的时区设置为特定值(同样,正如您所做的那样)。

It's common practice for computers to store all dates in GMT, and then adjust how they are displayed for the user. If you start trying to alter how the date is actually stored you are going to mess up a lot of date handling frameworks that are all assuming your NSDate is in GMT.

计算机通常会以 GMT 格式存储所有日期,然后调整它们向用户显示的方式。如果您开始尝试更改日期的实际存储方式,您将弄乱许多日期处理框架,这些框架都假设您的 NSDate 是 GMT。

As you have seen, when you read in a date via an NSDateFormatter, it's converted from the time entered based on the timezone of the formatter you have set, and then converted to GMT. So what do you think is wrong with what it is doing? Because it's doing just what it should - storing dates in GMT and outputting strings based on a timezone.

如您所见,当您通过 NSDateFormatter 读取日期时,它会根据您设置的格式化程序的时区从输入的时间转换,然后转换为 GMT。那么你认为它的做法有什么问题呢?因为它正在做它应该做的事情——以 GMT 格式存储日期并根据时区输出字符串。

回答by BoSoud

Try this

尝试这个

- (NSDate *) GetLocalDate {

    NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
    NSCalendar *theCalendar = [NSCalendar currentCalendar];
    theCalendar.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
    dayComponent = [[NSCalendar currentCalendar] components:NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];

    NSDate *localDate = [theCalendar dateFromComponents:dayComponent];

    return localDate;
}

- (void)viewDidLoad {
        [super viewDidLoad];
        NSLog(@"localDate : %@",[self GetLocalDate]);
}

回答by Mohd Iftekhar Qurashi

If you want local Date and time. Try this code:-

如果您想要本地日期和时间。试试这个代码:-

NSString *localDate = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];

回答by grep

Eliseo Chavez Jr answer translated to Swift

Eliseo Chavez Jr 的回答被翻译成 Swift

let sourceDate = NSDate();
let sourceTimeZone = NSTimeZone(abbreviation: "GMT")!;
let destinationTimeZone = NSTimeZone.systemTimeZone();
let sourceGMTOffset: NSInteger  = sourceTimeZone.secondsFromGMTForDate(sourceDate);
let destinationGMTOffset:NSInteger  = destinationTimeZone.secondsFromGMTForDate(sourceDate);
let interval: NSTimeInterval = Double (destinationGMTOffset - sourceGMTOffset);
let destinationDate = NSDate(timeInterval: interval, sinceDate: sourceDate);

回答by James Toomey

This works well for me to get the date in my timezone and format it just like I want it:

这对我来说很有效,可以在我的时区中获取日期并按照我想要的方式对其进行格式化:

NSDate* gmtDate = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/Los_Angeles"]];
[formatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
NSString *dateString = [formatter stringFromDate:gmtDate];