Ios NSDateFormatter是如何工作的?

Ios NSDateFormatter是如何工作的?,ios,objective-c,nsstring,nsdate,nsdateformatter,Ios,Objective C,Nsstring,Nsdate,Nsdateformatter,我已经创建了一个如下方法,在这个方法中我可以发送dateString、InputFormat和OutputFormat以及以下内容 - (NSString *)InstanceAwesomeFormatterunformattedDate:(NSString*)unformattedDate inputFormat:(NSString*)inputFormat outPutFormat:(NSString*)outPutFormat{ //unformattedDate is 13 j

我已经创建了一个如下方法,在这个方法中我可以发送dateString、InputFormat和OutputFormat以及以下内容

- (NSString *)InstanceAwesomeFormatterunformattedDate:(NSString*)unformattedDate inputFormat:(NSString*)inputFormat outPutFormat:(NSString*)outPutFormat{

    //unformattedDate is 13 july 1989
    //inputFormat is @"dd MMMM yyyy" 
    //outPutFormat is @"dd"

    NSDateFormatter *myDateFormattr = [[NSDateFormatter alloc] init];

    [myDateFormattr setDateFormat:inputFormat];

    NSDate *date = [myDateFormattr dateFromString:unformattedDate];
    //Why date is 1990-07-12 18:30:00 +0000
    [myDateFormattr setDateFormat:outPutFormat];

    NSString *FinalExpiryDateForUserProfile = [myDateFormattr stringFromDate:date];
    // FinalExpiryDateForUserProfile is 13 which is correct
    return FinalExpiryDateForUserProfile;

}
我试图理解为什么date打印的是12而不是13。 任何想法都需要使用区域设置

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd"];
NSLocale *enLocale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:enLocale];
您需要使用区域设置

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd"];
NSLocale *enLocale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:enLocale];

问题在于时区,您可以这样设置时区:

NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

您可以根据需要添加任何时区,而不是
GMT
。如果您根据自己的设置设置了正确的时区,那么设置
NSLocale
并不是必须的。

问题在于时区,您可以这样设置时区:

NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

您可以根据需要添加任何时区,而不是
GMT
。如果您根据自己的设置设置了正确的时区,那么设置
NSLocale
并不是必须的。

谢谢Fahim,但之前我尝试了YYYY而不是YYYY,这有区别吗?如果这个方法是一个类方法,它不会有任何区别,或者会有什么区别?请解释一下,谢谢again@ios_Dev:您必须使用YYYYTANKS Fahim,但之前我尝试使用YYYY而不是YYYY,这有什么区别吗?如果这个方法是一个类方法,它不会有任何区别,或者会有什么区别?请解释一下,谢谢again@ios_Dev:您必须使用YYYYthanks,先生,让我们假设对于印度时区,我将分配什么来代替@“GMT”?如果是印度时区,那么它应该与@“GMT”一起工作。我说的是设置不同的时区,也就是说,GMT、PST或UTC等时区。对于印度时区,格林尼治标准时间应该有效。如果你想根据设备时区设置时区,请参考以下内容:谢谢,先生,那么让我们假设印度时区,我会指定什么来代替“GMT”?如果是印度时区,那么它应该与“GMT”一起工作。我说的是设置不同的时区,也就是说,GMT、PST或UTC等时区。对于印度时区,格林尼治标准时间应该有效。如果要根据设备时区设置时区,请参考以下内容: