Pregunta

i have a method the receives NSDate object and returns the seconds from 1970.

it looks like this :

-(int)editDate:(NSDate*)date{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:date];


NSDateFormatter *stringToNSdate = [[NSDateFormatter alloc] init];
[stringToNSdate setTimeZone:[NSTimeZone systemTimeZone]];
[stringToNSdate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [stringToNSdate dateFromString:dateString];


return [dateFromString timeIntervalSince1970];
}

the method should return the seconds from 1970 minus or plus the UTC value. the first part until dateString is works fine, but then i need to make NSDate object from NSString and the formatter reduces the UTC value again. what am i doing wrong? there is an easy way?

¿Fue útil?

Solución

If I understand your problem correctly, your code should work, and also seems to give the expected result when I try it. Perhaps it is an issue of systemTimeZone versus localTimeZone.

But note that you can simplify the complete method to

NSTimeInterval i = [date timeIntervalSince1970];
i -= [[NSTimeZone localTimeZone] secondsFromGMTForDate:date];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top