I'm parsing a weather XML that gives me the sunrise + sunset times for the user's location. I've parsed them as strings, and they look like this: 7:20 am and 5:34 pm, for example.
I then converted these two times into an NSDate by doing this:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"hh:mm a"];
NSDate *Sunrise = [dateFormat dateFromString:sunrise];
NSDate *Sunset = [dateFormat dateFromString:sunset];
NSDate *today = [NSDate date];
[dateFormat release];
Now I have three dates which I now want to compare to determine whether the current time is night or day. The problem is, when I NSLog the Sunrise and Sunset times I see that the year is 1970 on both the dates that came from strings. I don't know where to start on how to compare the dates. Any ideas?
Theres actually a pretty simple way to do this. NSDateFormatter has a method called setDefaultDate: which basically uses a given date object to fill in any fields not included by the date format string. So, using the variables from your sample:
[dateFormat setDefaultDate:today];
Just put this line before the calls to dateFromString:, and you should be good to go.
Reference: NSDateFormatter Class Reference
You may split up a NSDate into Date Components, you'll need a NSCalendar Object and tell it to give you a NSDateComponents Instance for your date.
Like so:
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:date];
NSLog(#"Parts: Day %d, Month %d, Year %d", [comps day], [comps month], [comps year]);
Instead of the example "unitFlags" you may OR together any of the NS*CalenderUnit Flags to get the corresponding elements into "comps". In your case it would be something like NSHourCalenderUnit | NSMinuteCalenderUnit .
Try altering your sunrise and sunset NSString variables to contain the current date. Something like "2010-12-15 7:20am". Once you parse that, your Sunrise and Sunset dates will be correct, and the comparison should be easy.
Related
I'm searching the correct way to get the actual date and time for a given place / timezone, and being able to compare it to a given date/time for that same place.
Let's say, for the example, Paris, that is GMT +1. As we now, Paris can also be GMT+2 because of daylight saving, but it's part of an exception as far as I know so it must be taken in account into the answer, but not taken as a general param. The important words here are "given place".
So, if I want to know what date and time it is at Sidney Australia, or Paris France, and get that date into an NSDate for being able to compare it with another NSDate that would represent another date/time in the same place, how may I do ?
I've read pages and pages of questions and answers with comments, even on accepted answer, that says from experienced users : not a good answer -1, wrong, not the correct way of doing this, absolutely wrong, ...
So, do you know the correct real way to do that ?
In a perfect world, that date/time would be absolute even if the user's phone is not at the good time and/or date and/or timezone, or anything that can be near that perfection without needing for that to connect to a date/time server.
I'm searching the correct way to get the actual date and time for a given place / timezone.
[NSDate date]returns a date object representing the current date and time, no matter where you are. NSDates are not subject to places or time zones. There is just one NSDate that represents now or any other moment for that matter, not different date objects for every time timezone. Therefore, you should not attempt to convert a date between time zones.
NSDate objects represent an absolute instant in time. Consider the following example of how two date representations in different time zones (9/9/11 3:54 PM in Paris and 9/9/11 11:54 PM in Sydney) are actually the same date.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/Paris"]];
NSDate *aDate = [formatter dateFromString:#"9/9/11 3:54 PM"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"Australia/Sydney"]];
NSDate *anotherDate = [formatter dateFromString:#"9/9/11 11:54 PM"];
NSLog(#"%#",anotherDate);
if ([aDate isEqualToDate:anotherDate]) {
NSLog(#"How about that?");
}
It logs that last message because 9/9/11 3:54 PM in Paris and 9/9/11 11:54 PM in Sydney are actually the same instant in time. When it is 9/9/11 3:54 PM in Paris, it is 9/9/11 11:54 PM in Sydney.
both gives in the debugger and NSLog 2011-09-09 14:26:02, but it's now 16:26 so I guess it should return 16:26:02 +0200
When it comes to output a date, bear in mind that NSDate's description method returns time in GMT and you need to use a NSDateFormatter to create a date string representing the local time in Paris, Sydney, etc. from a date:
NSDate *now = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"Australia/Sydney"]];
NSLog(#"%#",[formatter stringFromDate:now]); //--> 9/9/11 11:54 PM
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/Paris"]];
NSLog(#"%#",[formatter stringFromDate:now]); //--> 9/9/11 3:54 PM
ok, but if I want to know if that time is after 15:00, how may I test that ?
Create an NSDate object that represents today at 15:00 (local time) and compare it to "now":
NSDate *now = [NSDate date];
NSCalendar* myCalendar = [NSCalendar currentCalendar];
NSDateComponents* components = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:[NSDate date]];
[components setHour: 15];
[components setMinute: 0];
[components setSecond: 0];
NSDate *todayAt15 = [myCalendar dateFromComponents:components];
if ([now compare:todayAt15] == NSOrderedDescending) {
NSLog(#"After 15:00 local time");
}
It turns out #Oliver needed to check if it is after 15:00 in Paris so he needed to create a date that represents today at 15:00 Paris time (not local time). For an example on how to do that, see #Oliver's answer. Just to be clear, my third snippet of code shows how to check if it is after 15:00 local time.
After a big headache and starting to understand what NSDate is, I imagined that kind of solution. What do you think about that way of doing ?
// Now, an absolute date and time that represent now all around the world, that is made to play with
NSDate *now = [NSDate date];
// A specific calendar for a specific place in the world
NSCalendar* parisCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[parisCalendar setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/Paris"]];
// Now components seen from Paris
NSDateComponents* componentsNowInParis = [parisCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit fromDate:now];
// Tricking a copy of "Now components seen from Paris" to force 15:00:00, in Paris
NSDateComponents* componentsInParisAt15 = [[componentsNowInParis copy] autorelease];
[componentsInParisAt15 setHour:15];
[componentsInParisAt15 setMinute:0];
[componentsInParisAt15 setSecond:0];
// Getting an universal date reference that represent what could be 15:00:00 seen from paris, Or 19:00:00 from GMT+4
NSDate* dateAt15 = [parisCalendar dateFromComponents:componentsInParisAt15];
// We now have two universal dates that can be compared each other
// If "now" is 16:00:00, those date will show a 60 minutes difference all around the world
NSLog(#"%#", now);
NSLog(#"%#", dateAt15);
Some reference : http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtTimeZones.html#//apple_ref/doc/uid/20000185-SW4
But, as far as I know and tested, that day/time cannot be really absolute. It is based on the iPhone date/time/timezone, that can be wrong.
Use NSCalendar, and the setTimeZone method.
NSDate *newDate;
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:~ NSTimeZoneCalendarUnit fromDate:[NSDate date]];
newDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
NSLog(#"newDate: %#", newDate);
NSLog(#"newDate: %.0f", [newDate timeIntervalSinceReferenceDate]);
newDate: 2011-09-09 15:02:09 +0000
newDate: 337273330
[dateComponents setTimeZone:[NSTimeZone timeZoneWithName:#"Australia/Sydney"]];
newDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
NSLog(#"newDate: %#", newDate);
NSLog(#"newDate: %.0f", [newDate timeIntervalSinceReferenceDate]);
newDate: 2011-09-09 00:52:03 +0000
newTimeInterval: 337222930
[dateComponents setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/Paris"]];
newDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
NSLog(#"newDate: %#", newDate);
NSLog(#"newDate: %.0f", [newDate timeIntervalSinceReferenceDate]);
newDate: 2011-09-09 08:52:03 +0000
newTimeInterval: 337251730
I searched it a lot but coudn't find any instance of showing how to store the specified time. For example, i need to save time of 15:48 in code in a proper variable (i guess that should be NSDate object). That is needed because i want to hold the exact time to replace the method below with not the time interval since now but my exact specified time to fire notification. Thanks for the help.
NSDate *notificationDate = [NSDate dateWithTimeIntervalSinceNow:5];
notification.fireDate = notificationDate;
Use NSDateComponents:
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour:15]; // 15:48 from your example
[comps setMinute:48]; // 15:48 from your example
/// also set year, month and day
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];
You can also use NSDateCompnents to read the components from the current date and time - so if you want to set an NSDate to 15:48 today, you would first create an NSDate for now and then extract the day, month and year from it but overwrite the hour and minutes.
Use NSDateComponents to generate an NSDate object. I guess the Apple document is what you want http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateComponents_Class/Reference/Reference.html
Take a look at NSDateFormatter and especially - (NSDate *)dateFromString:(NSString *)string
Alright I've given up on this. Here's what I'm trying to do: I have a sunrise, sunset, and the current time in a certain timezone. I want to know if it's day or night by figuring out if the current time lies between the sunrise and the sunset times.
Here's what I have:
NSLog(#"%# - %# - %#",currTime,sunrise,sunset);
NSDateFormatter *formatter1 = [[NSDateFormatter alloc]init];
NSDateFormatter *formatter2 = [[NSDateFormatter alloc]init];
[formatter1 setDateFormat:#"hh:mm a"];
[formatter2 setDateFormat:#"EEE, dd MMM yyyy h:mm a z"];
NSDate *rise = [formatter1 dateFromString:sunrise];
NSDate *set = [formatter1 dateFromString:sunset];
NSDate *time = [formatter2 dateFromString:currTime];
[formatter1 release];
[formatter2 release];
unsigned int flags = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components1 = [calendar components:flags fromDate:rise];
NSDateComponents *components2 = [calendar components:flags fromDate:set];
NSDateComponents *components3 = [calendar components:flags fromDate:time];
NSDate *Sunrise = [calendar dateFromComponents:components1];
NSDate *Sunset = [calendar dateFromComponents:components2];
NSDate *Time = [calendar dateFromComponents:components3];
NSLog(#"\nSunrise: %# \nSunset:%# \nTime:%#",rise,set,time);
NSLog(#"\nSunrise: %# \nSunset:%# \nTime:%#",Sunrise,Sunset,Time);
Here's the first output:
Fri, 10 Jun 2011 4:00 am SAST - 7:46 am - 5:41 pm
And here's the second (before making it only concerned about the time, not date)
Sunrise: 1969-12-31 22:46:00 +0000
Sunset: 1970-01-01 08:41:00 +0000
Time: 2011-06-10 02:00:00 +0000
And finally here is the last output (notice how the times are messed up?):
Sunrise: 0001-12-31 22:27:01 +0000
Sunset: 0001-01-01 08:22:01 +0000
Time: 0001-01-01 01:41:01 +0000
So I wanted to pop those resulting dates into my method that checks whether it's in between the dates:
+(BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate {
return (([date compare:beginDate] != NSOrderedAscending) && ([date compare:endDate] != NSOrderedDescending));
}
However, until I get the date problem figured out that method won't work. :/ I need help! What am I doing wrong?
Ok, so I gave up on trying to get NSDates to work for me. The timezone issues just killed my brain for the weekend. Anyway, I decided to use BoopMeister suggestion, but it doesn't work quite like I expect. Here's an example:
Using the setup from above, I added these lines:
NSInteger riseHour = [components1 hour];
NSInteger setHour = [components2 hour];
NSInteger timeHour = [components3 hour];
NSLog(#"Rise: %i Set: %i Time: %i",riseHour,setHour,timeHour);
Now, when I plug in these variables:
Current time: Fri, 10 Jun 2011 9:07 am CDT
Sunrise: 6:33 am
Sunset: 8:32 pm
However, when I output the strings from the methods above here's what I get:
Rise: 6 Set: 20 Time: 23
What the?
I would use the components you already have and not make new dates.
Starting at this point in your code:
NSDateComponents *riseComponents = [calendar components:flags fromDate:rise];
NSDateComponents *setComponents = [calendar components:flags fromDate:set];
NSDateComponents *timeComponents = [calendar components:flags fromDate:time];
And then something like
NSInteger riseHour = [riseComponents hour];
NSInteger setHour = [setComponents hour];
NSInteger timeHour = [timeComponents hour];
// Do some checks here
// If necessary do the same for the minutes ([components minute])
Comparing dates has been a performance issue in my app and since you already have the dateComponents it would be faster to make your own check and use the NSIntegers.
Okay, so as can be seen in the question, it gives the numerical presentation of the hours. Same works for the minutes. Build your checks after that.
What probably is the problem with the current time, is the calendar you use. It automatically converts the time to the time in the timezone of the calendar you use. You can also create a calendar with a string representation of the timezone. It's in the API of NSCalendar I think. Then after you made that calendar, then use that one for the current time.
One of the key things about NSDate is that it is in GMT. Always. However when you log it, it prints according to the user's locale.
Now when you do,
NSDateFormatter *formatter1 = [[NSDateFormatter alloc]init];
[formatter1 setDateFormat:#"hh:mm a"];
NSDate *rise = [formatter1 dateFromString:sunrise];
NSDate *set = [formatter1 dateFromString:sunset];
[formatter1 release];
You are just providing information about hour, minute and whether it is AM/PM. How is it to know which day the time belongs to. It fills this lack of information by defaulting to 01/01/1970 and timezone based on the user's locale. You do provide the timezone information in the current time which might or might not be the same as the user's locale.
To fix this, you must generate a string that includes the date and timezone info for the sunset time and pass it to the date formatter with the correct format to get the date. I am assuming you must've this (or how else will you know that it is the sunset or sunrise time for that day?). Since you know the place you should be able to get the timezone info as well. Once you've the correct information to build the dates with, every comparison method that you've used will work.
I am writing a categorie in Xcode, that would extend the current NSDate class. I want to add two methods which I use regularly and somehow I can't get them to work properly.
Currently I have this code:
+ (NSDate*) today
{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todayComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];
NSInteger theDay = [todayComponents day];
NSInteger theMonth = [todayComponents month];
NSInteger theYear = [todayComponents year];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:theDay];
[components setMonth:theMonth];
[components setYear:theYear];
NSDate* todayDate = [gregorian dateFromComponents:components];
[components release];
[gregorian release];
return todayDate;
}
I want it to return a date like this: "2010-11-03 00:00:00 +01". But somehow the timezone keeps buggin me, because this code returns "2010-11-02 23:00:00 +0000".
Can anyone tell me how to fix this code to actually return the correct date? Or can I just use this date and my application will convert it itself because of the timezone the machine is set to.
I have to log certain events in my app to a database, which also just uses the [NSDate date] method. Does that mean that the [NSDate date] method also uses the time without timezone information?
EDIT:
I think it has something to do with the Daylight savings time bug. The things I see is exactly the same as probably the Clock app has, with the bug making people wake up late. Also, the TimeZone defaults to the TimeZone currently set on your device, so it should stay the same until you change the timezone in your settings screen.
EDIT2:
Ok, some more tests:
NSLog(#"CurrentDate: %#", [NSDate date]);
NSLog(#"TZ: %#", [NSTimeZone defaultTimeZone]);
Gives me the following results:
2010-11-03 23:23:49.000 App[8578:207] CurrentDate: 2010-11-03 22:23:49 +0000
2010-11-03 23:23:49.001 App[8578:207] TZ: Europe/Amsterdam (GMT+01:00) offset 3600
See Using Time Zones. You'll want to set the calendar's time zone using NSCalendar's -setTimeZone: method before you start asking it for dates.
This is an interesting question and I worked at a solution for many hours. These are my findings:
NSLog(#"CurrentDate: %#", [NSDate date]);
The code shown above will have the same result as the code shown below:
NSLog(#"CurrentDate: %#", [[NSDate date] description]);
Reading through the NSDate Class Reference produces this documentation on the NSDate's description method.
The representation is not guaranteed to remain constant across different releases of the operating system. To format a date, you should use a date formatter object instead (see NSDateFormatter and Data Formatting Guide)
I also ran across the documentation for descriptionWithLocale: (id) locale:
“Returns a string representation of the receiver using the given locale.”
So, change your code
NSLog(#"CurrentDate: %#", [NSDate date]);
To:
NSLog(#"CurrentDate: %#", [[NSDate date] descriptionWithLocale:[NSLocale currentLocale]]);
Which should result in what you are looking for. And I can also prove that the [NSDate date] really give's the correct date, but is just being displayed with wrong method:
We can use the [today] (Wim Haanstra) to create two dates.
dateLastDay: 2010-11-02 23:59:00 +01
dateToday: 2010-11-03 24:01:00 +01
Then we use the code below to show the two dates:
NSLog(#"CurrentDate: %#", dateLastDay);
NSLog(#"CurrentDate: %#", dateToday);
Or:
NSLog(#"CurrentDate: %#", [dateLastDay description]);
NSLog(#"CurrentDate: %#", [dateToday description]);
The two groups show the same results, like this: "2010-11-02 22:59:00 +0000" and "2010-11-02 23:01:00 +0000". It looks like the two dates have the same ‘day’, but really?
Now we compare the days of the dates:
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit;
NSDateComponents *lastDayComponents = [gregorian components:unitFlags fromDate:dateLastDay];
NSDateComponents *todayComponents = [gregorian components:unitFlags fromDate:dateToday];
NSInteger lastDay = [lastDayComponents day];
NSInteger today = [todayComponents day];
return (lastDay == today) ? YES : NO;
We will get NO! Although the two dates appear to have the same day, month and year, they DON'T. It only appears that way because we displayed them in the wrong way.
Did you try using:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
todayAtOO = [formatter dateFromString:[formatter stringFromDate:[NSDate date]]];
I'm still trying to figure out exactly why this bug happens, but I do know a solution. Setting the timezone of your NSCalendar to GMT before sending it dateFromComponents: will solve the issue.
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
PS if there's a different solution that you found based on Joshua's suggestion, could you let us know what it is? It seems like you've solved the issue since you accepted his answer, but it's not really clear what you did. Thanks!
As far as I can see, it is giving you the correct answer if your timezone is GMT+1. Midnight your time is 23:00 the day before in GMT.
The problem is probably in formatting the returned date for output. It's given you a string for GMT instead of your current locale.
I am looking for component that can handle a spesific date.
what i am trying to do is to get Astring fron sever that represent date(for example 04-08-2012) in my iphone i want to be able to "work" with this date. such to compare it to another date , check if the date in the past or future and to print it to the app GUI
i tried work with NSDate but i didnt found how can i set a spesific date?
thanks
You can use an NSDateFormatter
Here is a sample code to parse a date from string:
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"%A, %B %d, %Y"];
NSDate* date = [formatter dateFromString:aString];
[date compare:anotherDate];
More about Date Formatter here
The date format string is composed of various elements that pull out portions of the date. %A is the full name of the day of the week, %B is the full name of the month, etc.
You need 3 classes to set the date by representation:
NSCalendar* cal = [NSCalendar currentCalendar]; // 1.
NSDateComponents *comps = [[NSDateComponents alloc] init]; // 2.
[comps setYear:2012];
[comps setMonth:4];
[comps setDay:8];
NSDate* date = [cal dateFromComponents:comps]; // 3.
[comps release];