objective c - Convert the exact NSString value to NSDate -


this question has answer here:

this code.

nsstring *datestring = @"2015-06-03 02:19:37";  nsdateformatter *formatter = [nsdateformatter new]; [formatter setdateformat:@"yyyy-mm-dd hh:mm:ss"];  nslog(@"converted date = %@",[formatter datefromstring:datestring]); 

the output of code above is: "converted date = 2015-06-02 18:19:37 +0000". know because converts nsstring respect gmt, wanted happen nsdate must 2015-06-03 02:19:37, same datestring

i know because [the nsdateformatter] converts nsstring respect gmt…

no, you're wrong. nsdateformatter defaults using current time zone.

what you're not understanding "2015-06-02 18:19:37 +0000" is same date , time "2015-06-03 02:19:37" (in local time zone, must gmt+0800).

also, description logged 1 representation of date. date not have year, month, day-of-month, hour, minute, second, or of that. date object represents moment in time. such moments don't have of , neither nsdate objects. representations of moments have things, , arrived @ processing date through specific calendar , time zone. in case, given date has multiple representations. because description gets logged happens choose representation weren't expecting doesn't mean date wrong.

you have implicitly requested conversion nsdate object string when logged it. that's because logging involves strings. string-formatting code used nslog() , %@ format specifier uses -description method. never going able force nsdate's implementation of -description use time zone, don't try.

if need string representation (and you're not debugging) , want in specific time zone or otherwise want dictate format, don't rely on -description method are. instead, use date formatter convert nsdate nsstring explicitly, , configure date formatter produce representation want.

but don't confuse need date being wrong.


what wanted check if given nsdate past 9pm est (-4gmt), while i'm on +8gmt timezone.

so, use nscalendar, nstimezone, , nsdatecomponents construct nsdate 9pm est (on current day, suppose mean) , compare dates.

nsdate* date = /* ... */; nscalendar* calendar = [[nscalendar alloc] initwithidentifier:nscalendaridentifiergregorian]; calendar.timezone = [nstimezone timezonewithname:@"america/new_york"]; nsdate* deadline = [calendar datebysettinghour:21 minute:0 second:0 ofdate:date options:0]; if ([date compare:deadline] == nsordereddescending)     /* date after deadline */; 

here used convenience method -datebysettinghour:minute:second:ofdate:options: , avoided direct use of nsdatecomponents. if needs differ, might have convert date date components using calender, modify components, convert them date, , compare.


Comments