我知道这是一个非常有问题,之前曾多次问过。但这是我每次都被困住的事情。
现在,我想转换来自阿根廷本地区域(UTC-3:0
)的Web服务的日期字符串,并希望将其转换为设备本地时区(假设为UTC+5:30
)。这是我的代码
-(NSDate *)getLocaDateStringFromDate:(NSString *)sourceDate andSourceTime:(NSString *)sourceTime
{
//sourceDate is @"2015-10-16"; and sourceTime is @"00:00:00"
static NSDateFormatter* df = nil;
if (!df) {
df = [[NSDateFormatter alloc]init];
df.dateFormat = @"yyyy-MM-dd HH:mm:ss";
}
NSString* source = [sourceDate stringByAppendingString:[NSString stringWithFormat:@" %@", sourceTime]];
NSTimeZone *sourceZone = [NSTimeZone timeZoneWithAbbreviation:@"ART"];
[df setTimeZone: sourceZone];
NSDate *ds = [df dateFromString:source];
NSLog(@"sourceZone time is %@" , [df stringFromDate: ds]);//sourceZone time is 2015-10-16 00:00:00, correct!
NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone];
[df setTimeZone: localTimeZone];
NSLog(@"local time is %@" , [df stringFromDate: ds]);//local time is 2015-10-16 08:30:00,, correct
NSString* str = [df stringFromDate: ds];
return [df dateFromString:str]; //this return 2015-10-16 03:00:00 +0000, why?
}
我的问题是,无论我的时区设置为UTC
,我的方法都会在systemTimeZone
中返回日期。我得到正确的字符串,但日期不正确。
任何帮助都将不胜感激。
答案 0 :(得分:2)
1。)首先,创建一个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];
。
NSDateFormatter
2。)将日期字符串转换为NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormat setDateFormat:@"M/d/yy 'at' h:mma"];
NSString* localTime = [dateFormat stringFromDate:destinationDate];
NSLog(@"localTime:%@", localTime);
。
Fnc_MyFunc(@myDate)
3)指定您要转换日期的本地和目的地时区。
获取源日期的时区:
date
获取用户时区:
user_id | count_laps
--------+-----------
1 | 85
2 | 37
5 | 55
12 | 48
4。)计算源时区和用户时区之间的inverval,如下所示:
user_id | [2015-10-01] | [2015-10-02] | [2015-10-03] | ....
--------+--------------+--------------+--------------+--------------
1 | 85 | 2 | 66 | ....
2 | 37 | 58 | 85 | ....
5 | 55 | 33 | 75 | ....
12 | 48 | 44 | 55 | ....
5.现在,为您要显示的格式化日期创建一个record, cursor, more = recordQuery.fetch_page(1000)
while more:
record, cursor, more = recordQuery.fetch_page(1000, start_cursor=cursor)
。
{{1}}
希望它对你有用:)