why date gets changed when i try to change formate? [duplicate] - iphone

This question already has an answer here:
NSDateFormatter not giving me correct
(1 answer)
Closed 9 years ago.
this is the code that i am using for changing date formate
NSLog(#"newBirthDates%#",_newwBirthDates);
NSDateFormatter *Form = [[NSDateFormatter alloc] init];
[Form setDateFormat:#"MM/dd"];
NSDate *date1 =[NSDate date];
NSString *string =[Form stringFromDate:date1];
NSLog(#"string%#",string);
NSDate *todaydate =[Form dateFromString:string];
NSLog(#"todaydate%#",todaydate);
this is what i get as output
newBirthDates(
"05/22",
"07/11",
"10/07",
"02/20"
)
newBirthDates(
"05/22",
"07/11",
"10/07",
"02/20"
)
string03/18
todaydate1970-03-17 18:30:00 +0000
now my question is why 3/18 become 03/17?? why one day get decreases

The answer is simple - time zones.
Take a close look at what NSLog prints out
1970-03-17 18:30:00 +0000
By default, a NSDateFormatter is set to your local timezone. That means, if your time zone is +5:30 giving it a date "1970/18/3" results in 1970-03-18 00:00:00 +0530.
However, NSLog always prints dates in GMT (zero) time zone, adding/substracting the time zone difference (5 hours and 30 minutes).
Basically, there is nothing to fix, you just have to understand how NSLog works if you want to use it to check NSDate values.

Your Log is showing as per string value, eliminating all important timezone differences.
Log of NSDate shows you the time from GMT.
And both the values are correct.
The sole primitive method of NSDate, timeIntervalSinceReferenceDate,
provides the basis for all the other methods in the NSDate interface.
This method returns a time value relative to an absolute reference
date—the first instant of 1 January 2001, GMT.
You must read NSDate Documentation.

for getting correct date you can use this one,
NSDateFormatter *Form = [[NSDateFormatter alloc] init];
[Form setDateFormat:#"MM/dd"];
[Form setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *date1 =[NSDate date];
NSString *string =[Form stringFromDate:date1];
NSLog(#"string%#",string);
NSDate *todaydate =[Form dateFromString:string];
NSLog(#"todaydate%#",todaydate);
above code will give the correct date.

The Main thing is TimeZone : [Form setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
This is the Correct Code :
NSDateFormatter *Form = [[NSDateFormatter alloc] init];
[Form setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[Form setDateFormat:#"MM/dd"];
NSDate *date =[NSDate date];
NSString *string =[Form stringFromDate:date];
NSDate *todaydate = [Form dateFromString:string];
NSLog(#"todaydate %#",todaydate);

Related

NSdate Assuming wrong time zone

I am trying to convert the following string into an NSDate object:
NSString *str=#"25 May 2012 10:25:00";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"d MMM yyyy HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"asia/kolkata"]];
NSDate *date = [dateFormatter dateFromString:str];
In console : date-->2012-05-25 04:55:00 +0000....it lags behind 5 hours and 30 minutes and assumes GMT timezone instead of Asia...Why it is so?
When you see an [NSDate description] printed in the console, it is always the corresponding time in GMT. If you use the same date formatter to convert the date back to a string, it should be in the specified time zone.
An [NSDate description] is what you see if you type
po date
or
po [date description]
or you use NSLog to send either one of these forms to the console.
if you are looking for India Timezone you should use:

NSDate independent of timezone?

I have an app that displays a timetable of certain ferry trips.
If I travel to a different timezone - say 4 hours behind, a 10am ferry trip now shows up as 6am?
I know this has got to do with how dates are treated based on their timezones, but I can't work out how to change that behaviour.
At the moment here's how I am getting the date and displaying it on a UILabel:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
[self.departureTime setText:[dateFormatter stringFromDate:[self.route objectForKey:#"departureTime"]]];
[self.arrivalTime setText:[dateFormatter stringFromDate:[self.route objectForKey:#"arrivalTime"]]];
[dateFormatter release];
Thanks in advance for your help.
You'll need to store the timezone that the ferry ride is taking place in and format it for that timezone.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
NSDate *now = [NSDate date];
NSLog(#"now:%#", [dateFormatter stringFromDate:now]);
NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:(-8 * 3600)];
[dateFormatter setTimeZone:timeZone];
NSLog(#"adjusted for timezone: %#", [dateFormatter stringFromDate:now]);
Outputs:
2011-10-10 20:42:23.781 Craplet[2926:707] now:20:42
2011-10-10 20:42:23.782 Craplet[2926:707] adjusted for timezone: 16:42
You have seen NSDateFormatter's setTimeZone method, yes?
http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDateFormatter/setTimeZone:
(b.t.w., I'd be amazed if there was a ferry that involved crossing four time zones; sounds like a cruise ship itinerary to me)
You can also use the NSDateComponents class as described by apple's reference:
If you need to create a date that is independent of timezone, you can store the date as an NSDateComponents object—as long as you store some reference to the corresponding calendar.
In iOS, NSDateComponents objects can contain a calendar, a timezone, and a date object. You can therefore store the calendar along with the components. If you use the date method of the NSDateComponents class to access the date, make sure that the associated timezone is up-to-date.
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtTimeZones.html#//apple_ref/doc/uid/20000185-SW1
Don't confuse an NSDate value with a formatted output like NSLog. NSDate is GMT, Apple's docs:
The sole primitive method of NSDate, timeIntervalSinceReferenceDate,
provides the basis for all the other methods in the NSDate interface.
This method returns a time value relative to an absolute reference
date—the first instant of 1 January 2001, GMT.
NSTimeInterval referenceInterval = [[dateFormatter dateFromString:#"1 January 2001 GMT"] timeIntervalSinceReferenceDate];
NSLog(#"referenceInterval: %f", referenceInterval);
NSTimeInterval estInterval = [[dateFormatter dateFromString:#"1 January 2001 EST"] timeIntervalSinceReferenceDate];
NSLog(#"estInterval: %f", estInterval);
Output:
referenceInterval: 0.000000
estInterval: 18000.000000
NSDate *currentDateTime = datePicker.date;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEE,MM-dd-yyyy HH:mm:ss"];
NSString *dateInStringFormated = [dateFormatter stringFromDate:currentDateTime];
NSLog(#"%#", dateInStringFormated);

NSDate is converting really strangely

I have a time: 7:46 am
I want to convert this to NSDate. I do this:
NSDateFormatter *f = [NSDateFormatter new];
[f setDateFormat:#"h:mm a"];
NSDate *sr = [f dateFromString:#"7:46 am"];
I NSLog sr and I get 1969-12-31 22:46:00 +0000
Those times are not the same. Why is this so messed up?
No. Its not strange. NSDateConverter & NSDate are just doing their intended job here.
You are trying to convert "7:46 am" into a date. It contains only the time. No date is specified in the string. NSDate will default to "1970-01-01"(Unix epoch) if no date is specified. So after you convert the string you will get the date "1970-01-01 7:46 am". When you trying to display this in NSLog, if will display the date after adjusting the timeZone offset value. I guess you live in Japan or Korea. Probably the offset of your region is +09:00. So it diaplays the date subtracting the offset. So you are seeing "1969-12-31 22:46:00 +0000" in the log.
You can use the following method to set that time to a particular date, may be today.
NSString *timeStr = #"7:46 am";
NSDateFormatter *f = [NSDateFormatter new];
[f setDateFormat:#"yyyy-MM-dd"];
NSString *dateStr = [f stringFromDate:[NSDate date]]; // dateStr = 2011-06-10
dateStr = [dateStr stringByAppendingFormat:#" %#", timeStr]; // dateStr = 2011-06-10 7:46 am
[f setDateFormat:#"yyyy-MM-dd h:mm a"];
NSDate *sr = [f dateFromString:dateStr];
You aren't providing the day or the timezone... assuming you want to express "today at 7:42am", you can use this code:
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour:7];
[comps setMinute:42];
NSDate *myDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[comps release];
The NSLog of myDate should give you the expected output now (assuming you wanted today#7:46am).
Since you are only specifying the time that you want the NSDate to refer to, and not the date, the formatter is using the default date (which seems to be very close to the UNIX epoch). Like Julio said, you should specify the current date as well, if you want the NSDate to refer to the time on that specific date.

Required NSDate in PST

I want current date and time in PST. I used this code
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss zzz"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"PST"]];
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
NSLog(#"String:%#",timeStamp);
It returns correct date and time in PST in string form but I want NSDate in PST. So when I change NSString to NSDate like this:
NSDate *currentPST = [dateFormatter dateFromString:timeStamp];
NSLog(#"currentPST Date:%#",currentPST);
It returns date in GMT. I have done R&D but all in vain.Output is:
String:2011-05-18 22:28:54 PDT
currentPST Date:2011-05-19 05:28:54 +0000
Can anyone suggest a solution please.
Thanks in advance
In Cocoa, NSDate is an abstract representation of a date with no time zone information applied.
Whenever you print a NSDate object, it will print the date value corresponds to the default timezone(your device timezone). Your device timezone is GMT thats why you get the value like that. If you look into that deeply, both the time where same, but the timezone varies.

How to compare just dates not the time?

How can I compare the dates only, not the time. I am using
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *tempDate = #"2-2-2012"; //Dynamic Date
NSDate *dateString = [dateFormatter dateFromString:tempDate];
NSLog(#"%#",dateString);
It logs this: 2012-02-01 18:30:00 +0000
NSDate *now = [NSDate date];//Current Date
NSLog(#"%#",now);
It logs this: 2011-04-04 14:49:45 +0000
I want to compare Dynamic date and current date, I don't need time. I may not using the correct NSDateFormatter. Can anyone of you tell me how to do this? If I am not clear, please let me know.
Suppose I have to strings
date1 = 3-2-2011;
date2 = 4-5-2020;
I want to convert them in date, only after that I can compare them. Its not happening from my date Formatter. Please have a look.
Thanks!
Simplest way is to compare date by converting it into string.
Sample Code is as shown below:
//Current Date
NSDate *date = [NSDate date];
NSDateFormatter *formatter = nil;
formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
NSString *dateString = [formatter stringFromDate:date];
[formatter release];
//Other Date say date2 is of type NSDate again
NSString *date2String = [formatter stringFromDate:date2];
//Comparison of Two dates by its conversion into string as below
if([date2String isEqualToString:dateString])
{
//Your logic if dates are Equal
}
else if(![date2String isEqualToString:dateString])
{
//Your Logic if dates are Different
}
EDIT:
Checkout this link.
Comparing dates
http://www.iphonedevsdk.com/forum/iphone-sdk-development/64625-how-compare-2-dates.html
Hope This Helps You. :)
Use NSCalendar and NSDateComponents to get a date components object. Then you can look at only those parts of the date that you care about.
If you're just trying to determine whether two dates are the same, regardless of time, one way to go is to use NSDate's -timeIntervalSinceDate: method. If the time interval returned is less than 86,400 seconds (i.e. 24 hours * 60 minutes * 60 seconds) then you can feel fairly sure that it's the same day. Changes related to such things as daylight savings time and leap seconds introduce some possibility of error... if that's a problem, go with NSDateComponents.
NSDate *date = [NSDate date];
NSDateFormatter *formatter = nil;
formatter=[[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setLocale:[NSLocale autoupdatingCurrentLocale]];
NSString *dateString = [formatter stringFromDate:date];
[formatter release];