how to change nsdate in nsdictionary - iphone

I am trying to increment my NSDate. I have an NSDictionary, I am trying to increment my NSDate content in it. Say my NSDate is 2011-07-11, I want to increment the NSDate content in it.
got
{
ConditionDatenew = "2011-07-21 13:31:46 +0000";
Yesterday = "2011-07-20 13:31:46 +0000";
city = #;
condition = "Isolated Thunderstorms";
country = #;
"day_of_week" = Sun;
high = 86;
icon = "chance_of_storm.gif";
low = 68;
state = #;
}
I just want to get the date as 2011-07-22 in my ConditionDatenew in the next dictionary loop. How can I get it?

Create a new date object, and replace the old value in the dictionary. Dates are immutable.
NSDate *newDate = [NSDate date];
[dictionary setObject:newDate forKey:#"ConditionDatenew"];
[NSDate date] will set this to "now."
The easiest way to add a day is to add 24 hours. This works as long as DST is never an issue, and by "increment a day" you mean "increment by 24 hours." If you work exclusively in UTC, then that's fine.
NSDate *newDate = [oldDate dateByAddingTimeInterval:24*60*60];
If DST is an issue (and it usually is), and by "increment a day" you mean "increment by a Gregorian calendar day" then you need to use date components to make sure you add 23, 24 or 25 hours as appropriate.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear:2011];
[dateComponents setMonth:11];
[dateComponents setDay:6];
[dateComponents setTimeZone:[NSTimeZone timeZoneWithName:#"America/New_York"]];
NSDate *date = [calendar dateFromComponents:dateComponents];
NSDateComponents *addComponents = [[NSDateComponents alloc] init];
[addComponents setDay:1];
[addComponents setTimeZone:[NSTimeZone localTimeZone]];
NSDate *newDate = [calendar dateByAddingComponents:addComponents toDate:date options:0];
NSLog(#"oldDate=%#", [date descriptionWithLocale:[NSLocale currentLocale]]);
NSLog(#"+24=%#", [[date dateByAddingTimeInterval:24*60*60] descriptionWithLocale:[NSLocale currentLocale]]);
NSLog(#"newDate=%#", [newDate descriptionWithLocale:[NSLocale currentLocale]]);
[calendar release];
[dateComponents release];
[addComponents release];
Output:
oldDate=Sunday, November 6, 2011 12:00:00 AM Eastern Daylight Time
+24=Sunday, November 6, 2011 11:00:00 PM Eastern Standard Time
newDate=Monday, November 7, 2011 12:00:00 AM Eastern Standard Time
If you don't care about the time, and have control over what you set it to, one trick is to set the time to noon. That way adding 24 hours will always fall on the correct day. I don't generally recommend this because it fails badly if you ever forget and create a date with a time of midnight. It's easier to put all of your day-incrementing code in one place and fix the DST problem one time than to make sure all of your date creation code is always right. So I recommend getting used to date components.

Try this:
NSDate *newDate = [NSDate date];
[dictionary setValue:newDate forKey:#"ConditionDatenew"];

Related

Get first and last day of week for a couple of weeks

I need to make a calendar in which the user can scroll between several weeks. The first and last day of the week will be displayed like (e.g.) "June 4 - June 10".
Now I knew from the beginning that I'd need NSDate and NSCalendar, and indeed I managed to get the first and last day of just thist week, but it looks extremely cumbersome and I am sure there needs to be an easier method, as I need to get the dates for several more coming and past weeks.
This is my code which gives the day and month of the first and last day of the current week:
NSDate *today = [NSDate date];
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comp = [cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSYearCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit) fromDate:[NSDate date]];
NSDate *beginOfWeek = [today dateByAddingTimeInterval: -1*([comp weekday]-2)*24*3600];
NSDate *endOfWeek = [today dateByAddingTimeInterval:(7-[comp weekday]+2)*24*3600];
NSLog(#"beginWeekDay=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: beginOfWeek] day]);
NSLog(#"endWeekDay=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: endOfWeek] day]);
NSLog(#"beginWeekmonth=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: beginOfWeek] month]);
NSLog(#"endWeekmonth=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: endOfWeek] month]);
I found this, which may be helpful to you: http://www.cocoanetics.com/2009/11/add-one-week-skip-weekend/
- (NSDate *)addWeekToDateAndSkipWeekend:(NSDate *)now {
int daysToAdd = 6; // we'll add the 7th later
// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd];
// create a calendar
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *newDate = [gregorian dateByAddingComponents:components toDate:now options:0];
[components setDay:1]; // reuse to skip single days
NSDateComponents *newDateComps; // new componets to get weekday
// do always executed once, so we add the 7th day here
do
{
// add one day
newDate = [gregorian dateByAddingComponents:components toDate:newDate options:0];
newDateComps = [gregorian components:NSWeekdayCalendarUnit fromDate:newDate];
// repeat if the date is Saturday (7) or Sunday (1)
NSLog(#"weekday: %d", [newDateComps weekday]);
} while (([newDateComps weekday]==7)||([newDateComps weekday]==1));
return newDate;
}
Theoretically, you run this in a for loop with [NSDate date] and you will get the 7th day returned, you would then run the returned 7th day through this and get the next..etc..
May need minor alteration, to remove the check for Saturday+Sunday if you don't need it.
Hope this helps !

iPhone - Correct way for getting current date and time for a given place / timezone and compare it with another date/time in the same place

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

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.

NSDate troubles - or how to ignore date/timezone?

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.

How to change a date by changing AM / PM hours period in 12h format?

In the docs, Apple gives an example on how to add some hours and minutes to an existing date:
NSDate *today = [NSDate date];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setHour:1];
[offsetComponents setMinutes:30];
NSDate *endOfWorldWar3 = [gregorian dateByAddingComponents:comps toDate:today options:0];
But now, I have date which is printed out in 12h format with AM / PM (unicode standard format specifier is "a").
So I have an date object which is set to 8:00 'o clock, and now I want to switch that to PM or 20:00 'o clock. Hard to explain. NSDateComponents doesn't have a component for that.
The docs say that all these NSDateComponents things like hour, minute, day, etc. are in context with a calendar object. Makes sense. But I haven't found anything in NSCalender which would say "this is 12h format" or "this is 24h format".
So actually, what happens when I change the hour period? Isn't that actually just simple math to say "lets take 12 hours off, or lets add 12 hours"? Any idea?
NSDate is just a value for a moment in time. How you display it, whether it has PM or is in the 24 hour format, is in the formatting.
Here are some formatters:
k gives you 24-hour hours
a gives you AM/PM
From here.
Use the info on that page with NSDateFormatter, like this:
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:#"yyyy-MM-dd 'at' kk:mm"];
NSDate *formatterDate = [inputFormatter dateFromString:#"1999-07-11 at 22:30:03"];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:#"kk:mm 'on' EEEE MMMM d"];
NSString *newDateString = [outputFormatter stringFromDate:formatterDate];
NSLog(#"newDateString %#", newDateString);
// For US English, the output is:
// newDateString 22:30 on Sunday July 11