objective c and NSDate - iphone

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];

Related

How to get date from day of the year in iPhone?

How do I get date from the day of the year?
for e.g., if I give day as "1" then date should be "January 1"
How do I get that in iPhone? I have found answer in javascript but I want to know how to do the achieve same thing in Objective?
I guess this code will work for you:
I have created a sample function where a textfield gives input values for how many days to add. And a button to calculate final day. Here is the button event logic.
NSDateComponents *dateComponent = [[NSDateComponents alloc] init];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-mm-dd"];
NSDate *newDate = [formatter dateFromString:#"2012-01-01"];
// add days to current date
dateComponent.day = [dayTextField.text intValue];
// get a new date by adding components
newDate = [[NSCalendar currentCalendar] dateByAddingComponents: dateComponent toDate:newDate options:0];
[finalDate setText:[NSString stringWithFormat:#"%#", newDate]];
Here dayTextField.text is the text which says how many number of days want to calculated. (For example 125 days) and finalDate is an label which displays final generated date (means date after 125 days since 1 Jan 2012).
Benefit of this code is, any time you can change the start day parameter. For example, for other requirement, i need to count my days from "31 May 1999" then i will change it easily in one line and the same code will work.
Enjoy Coding :)
NSCalendar *gregorian =
[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger dayOfYear =
[gregorian ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSYearCalendarUnit forDate:[NSDate date]];
[gregorian release];
return dayOfYear;
Take from the post:
How do you calculate the day of the year for a specific date in Objective-C?

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.

Convert String to Date and fetch the difference

hi i have 2 dates in string format
base_date_string = 10-12-01 12:00:00
current_date_string = 10-12-23 10:18:00
both the above values are in string
i want to get the number of days elapsed between these 2 dates
I tried to convert them to NSDate using NSDateFormatters and then getting the difference.
I realised that string does not properly converts to NSDate
when i convert to nsdate i got
base_date:::2010-12-01 06:30:00 +0000
current_date::::2010-12-23 04:48:19 +0000 (the time portion is not perfect)
Formatter class that i used is:
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:#"yy-MM-dd HH:mm:ss"];
NSDate *base_date = [formatter1 dateFromString:#"10-12-01 12:00:00"];
[formatter1 release];
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:#"yy-MM-dd HH:mm:ss"];
NSDate *current_date = [formatter2 dateFromString:current_date_string];
[formatter2 release];
//subrtrcation of basedate from current date to get elapsed number of days
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *diff = [calendar components:(NSDayCalendarUnit)
fromDate:base_date toDate:current_date options:0];
int date_value = [diff day];
Please any help is appreciated
30 seconds in the NSDate documentation revealed:
-[NSDate timeIntervalSinceDate:]
So using the dates in your question...
NSTimeInterval difference = [current_date timeIntervalSinceDate:base_date];
difference = fabs(difference);
NSLog(#"there are %f seconds between %# and %#", difference, current_date, base_date);
edit
ok, so the problem is not date differencing. You're observing that the string you're inputting is 5 and 1/2 hours ahead of the date you're getting back.
Well, let's look at this. The date returned is in GMT time (as denoted by the +0000). 5 and 1/2 hours ahead of that is the timezone used in India. So. Are you in India? If you are, then this is just a matter of needing to -setTimezone: on your NSDateFormatter.
You can use this code of function to get the difference between 2 dates
-(int)howManyDaysHavePast:(NSDate*)lastDate :(NSDate*)today {
NSDate *startDate = lastDate;
NSDate *endDate = today;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlags = NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:startDate
toDate:endDate options:0];
[gregorian release];
int days = [components day];
return days;
}
hAPPY iCODING...
Use the following code
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:#"yy-MM-dd HH:mm:ss"];
NSDate *base_date = [formatter1 dateFromString:#"10-12-01 12:00:00"];
NSDate *current_date = [formatter2 dateFromString:current_date_string];
[formatter1 release];
NSTimeInterval difference = [current_date timeIntervalSinceDate:base_date];
Then you will get difference in number of seconds. Then you can get in number of days as following
float days = difference/86400;
The "days" consists the number of days that the current_date is differ from the base_date.

Comparing NSDates to determine day or night?

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.

NSCalendar to Display Weekday

Im using an NSCalendar to display the week day, I have no problem displaying the weekday in an integer, but i am confused as to how i might get it to tell me the weekday, i.e. "Thursday." I read that %A, and %a might do the trick but I do not know how to implement them. My code is below.
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:now];
NSInteger weekday = [weekdayComponents weekday];
myLabel.text = [NSString stringWithFormat:#"%02d", weekday];
I use myLabel to display the string on the Iphone, but if there is a better way please let me know.
Thanks for the help.
James
To display day of week you actually need to use NSDateFormatter class, set 'EEEE' format to get full day name (like Thursday) or 'EEE' - for shortened (like Thu). Very sample code:
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"EEEE"];
NSLog([f stringFromDate:[NSDate date]]);