2

我已经用美国地区格式测试了我的应用程序,并且日期显示是正确的。当区域更改为我现在居住的意大利时包含空值。

我的起始字符串日期是:-“2013 年 5 月 2 日下午 6:46:33”

结果日期正确的是:-“02/05/2013 18:46:33”

这是我的代码:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 dateFormatter setDateFormat:@"MM dd, yyyy hh:mm:ss a"];


 NSDate *dateFromString;
 dateFromString = [dateFormatter dateFromString:dataStr];

 [dateFormatter setDateFormat:@"dd/MM/yyyy HH:mm:ss"];
 dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];


 NSString *stringFromDate  = [dateFormatter stringFromDate:dateFromString];
4

2 回答 2

2

如果您的起始字符串是,May 2, 2013 6:46:33 PM那么您有两个问题:

  1. 您的格式字符串MM dd, yyyy hh:mm:ss a与您的字符串不匹配。它需要是MMMM dd, yyyy hh:mm:ss a。用于MM数字月份。用于MMM缩写的月份名称和MMMM完整的月份名称。
  2. 您的日期字符串有英文月份名称。如果您的设备是为意大利设置的,那么它将无法正确解析月份名称,因为它会期望月份名称为意大利语。

您的代码应该是:

NSString *dateStr = @"May 2, 2013 6:46:33 PM";
NSDateFormatter *inputDateFormatter = [[NSDateFormatter alloc] init];
[inputDateFormatter setDateFormat:@"MMMM dd, yyyy hh:mm:ss a"];
[inputDateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];

NSDate *dateFromString = [inputDateFormatter dateFromString:dataStr];

NSDateFormatter *outputDateFormatter = [[NSDateFormatter alloc] init];
[outputDateFormatter setDateFormat:@"dd/MM/yyyy HH:mm:ss"];

NSString *stringFromDate  = [outputDateFormatter stringFromDate:dateFromString];
于 2013-05-02T17:20:41.253 回答
0

用这个:

NSDate* sourceDate = your_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];

希望它可以帮助你。

于 2013-05-02T16:57:56.897 回答