问题
I have a string, that I know will be reference to an UTC timestamp
@"2016-01-20T17:00:00"
now when converting it to an actual NSDate it returns this when printed out:
NSLog("%@", [TimeHelper stringToDateInUtc:@"2016-01-20T17:00:00"]);
-> 2016-01-20 18:00:00 +0000
Same thing with a UTC date:
NSLog(@"Time in UTC Now: %@", [TimeHelper getNowUtcAsDate]);
I also have this method for getting the current time in UTC and convert the string to UTC:
+ (NSDate*) stringToDateInUtc:(NSString*)str
{
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
return [formatter dateFromString:str];
}
+ (NSString*) getNowUtc
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *now = [[NSDate alloc] init];
return [formatter stringFromDate:now];
}
+ (NSDate*) getNowUtcAsDate
{
return [TimeAndDate stringToDateInUtc:[TimeAndDate getNowUtc]];
}
I am doing a calculation off time difference and since I know that the string that gets sent to these methods are absolutely in "UTC" mode. Therefor I need to compare it to an actual UTC date time.
So, why does the strings I input get converted to the wrong timezone - even though they're set as UTC. And also, UTC time from the method is almost always wrong - lots of reference to other posts here. If I reset my clock -2 hours, the UTC timestamp is also -2 hours, which it shouldn't - reason why I'm using UTC as a reference.
Or is it just the output that's wrong? Instead, maybe use the "timeSinceDate" methods to do the calculations?
Point is that no matter if I put the clock back, UTC time will always be right and the string to calculate time since or until current UTC time is always in UTC.
来源:https://stackoverflow.com/questions/34909745/utc-string-to-date-and-utc-time-calculations