ios - NSDate returning different value on conversion from string - Not GMT related -


i hope isn't gmt related or feel rather stupid.

2 quick related questions. why converting different date? losing day. looked @ time zones stated in other answers gmt timezone 0000 expected. presume error in setdateformat can't see how fix it.

nsstring *stringfromdate = self.datelabel.currenttitle; nslog(@"stringfromdateweight! %@", stringfromdate);  nsdateformatter *df = [[nsdateformatter alloc] init]; //convert nsdate [df setdateformat:@"ddmmyyyy"];  nsdate *inputeddate = [df datefromstring: stringfromdate]; nslog(@"stringfromdateweight2! %@", inputeddate); 

nslog(@"stringfromdateweight! %@", stringfromdate); is
17072013

nslog(@"stringfromdateweight2! %@", inputeddate);   

2013-07-16 23:00:00 +0000

i using code below compare 2 dates , right in returns in seconds? how change return in days?

int intervall = (int) [thedate timeintervalsincedate: now]; 

if don't explicitly set timezone nsdateformatter use local timezone. don't set one, formatter create nsdate @ "midnight july 17" in timezone. description method of nsdate return date formatted in utc timezone. since "july 16 23:00:00" guess timezone utc+1.

you have 2 options. calculate in utc setting timezone explicitly.

df.timezone = [nstimezone timezoneforsecondsfromgmt:0]; 

or, more useful, don't @ description of nsdate , use [inputeddate descriptionwithlocale:[nslocale currentlocale]] debugging, print date formatted timezone.
if want display date user use nsdateformatter (preferably datestyle , timestyle , not dateformat, because hardcoded dateformats evil)

it's display different, underlying nsdate object still same.


regarding second question:

in many timezones there 2 days each year don't have 24 hours, can't calculate seconds timeintervalsincedate:.

you have use nsdatecomponents , nscalendar. fortunately there method want. components:fromdate:todate:options:

nscalendar *calendar = [[nscalendar alloc] initwithcalendaridentifier:nsgregoriancalendar]; nsdatecomponents *components = [calendar components:nsdaycalendarunit|nshourcalendarunit|nsminutecalendarunit|nssecondcalendarunit fromdate:inputeddate todate:[nsdate date] options:0]; nslog(@"date %d days (and %d hours, %d minutes , %d seconds) ago", components.day, components.hour, components.minute, components.second); 

if need number of days can remove components except nsdaycalendarunit


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -