【发布时间】:2015-01-05 15:52:32
【问题描述】:
我制作的移动应用程序使用来自我无法控制的 .NET 服务器的 Web 服务。
在安排不同时区的活动时,我们总是会遇到麻烦。
服务器处于美国东部标准时间,来自网络服务的大部分数据都以这种方式呈现。
我们最终不得不添加显示日期字段,这非常令人困惑。
此外,我的代码基本相同,只是它取决于我是在与服务器交谈还是在设备上进行计算。也是一种痛苦。
这是我为处理 EST 时间所做的一个示例:
数据传入:
- (void)initWithWebServiceData:(NSDictionary *)data {
self.scheduleDate = [self dateFromDotNetJSONString:data[@"ScheduleDate"]];
//...and other stuff
}
- (NSDate *)dateFromDotNetJSONString:(NSString *)stringInEST {
int secondsESToffset = 14400;
static NSRegularExpression *dateRegEx = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
dateRegEx = [[NSRegularExpression alloc] initWithPattern:@"^\\/date\\((-?\\d++)(?:([+-])(\\d{2})(\\d{2}))?\\)\\/$" options:NSRegularExpressionCaseInsensitive error:nil];
});
NSTextCheckingResult *regexResult = [dateRegEx firstMatchInString:stringInEST options:0 range:NSMakeRange(0, [stringInEST length])];
if (regexResult) {
// milliseconds
NSTimeInterval seconds = [[stringInEST substringWithRange:[regexResult rangeAtIndex:1]] doubleValue] / 1000.0;
// timezone offset
if ([regexResult rangeAtIndex:2].location != NSNotFound) {
NSString *sign = [stringInEST substringWithRange:[regexResult rangeAtIndex:2]];
// hours
seconds += [[NSString stringWithFormat:@"%@%@", sign, [stringInEST substringWithRange:[regexResult rangeAtIndex:3]]] doubleValue] * 60.0 * 60.0;
// minutes
seconds += [[NSString stringWithFormat:@"%@%@", sign, [stringInEST substringWithRange:[regexResult rangeAtIndex:4]]] doubleValue] * 60.0;
}
return [NSDate dateWithTimeIntervalSince1970:seconds - secondsESToffset];
}
return nil;
}
数据输出:
- (void)requestRegistrationForEvent
{
NSString *fullDateTime = [NSString stringWithFormat:@"%@ %@", [self.scheduleDate webServiceStringValue], [self.scheduleDate dateTimeText]];
[self.dataController requestRegistrationForEvent:[self.eventID stringValue]
onDate:fullDateTime];
}
- (NSString *)webServiceStringValue {
NSString *webServiceStringValue = nil;
if ([self isKindOfClass:NSDate.class]) {
NSDate *date = (NSDate *)self;
//format the date how the web service expects it
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"M/d/yyyy"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];
webServiceStringValue = [dateFormatter stringFromDate:date];
}
return webServiceStringValue;
}
- (NSString *)dateTimeText {
NSString *text = @"";
NSDate *date;
if ([self isKindOfClass:NSDate.class]) {
date = (NSDate *)self;
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"h:mm a"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[timeFormatter setTimeZone:gmt];
text = [timeFormatter stringFromDate:date];
text = [text lowercaseString];
text = [text stringByReplacingOccurrencesOfString:@" " withString:@""];
}
return text;
}
问题
我是否做错了什么?我可以向我的 .NET 合作伙伴推荐什么来处理时区?
【问题讨论】:
标签: ios .net timezone standards web-standards