iPhone - Calculating the Day of Week of any date - iphone

I have a NSDate variable "aDate" that represents a date, for example, sunday, August 28, 2011. I have this date on a NSDate variable. This can be any date, but the problem appears when the day is a sunday.
I want to obtain the three letter string representing the day of week. In this case, SUN.
Then I have this code:
NSDateFormatter* theDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[theDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[theDateFormatter setDateFormat:#"EEE"];
[theDateFormatter setLocale:currentLocale]; // I have tried to comment this out... no change
NSString *dayOfWeek = [theDateFormatter stringFromDate:aDate];
the result I have is MON. Monday?
The insanity just goes wilder if I add this code:
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:myDate];
int weekday = [comps weekday];
then weekday comes as 2 (MONDAY ??????) WTF? Confirming the problem.
I am on a locale that in theory monday is the first day of week. So, independently of my timezone any date just have one day of week. If I want to calculate what day of week was January 1, 1978, I shouldn't need to define any timezone.
How do I do that on iPhone?
thanks.

NSData is referenced to a base date "the first instant of 1 January 2001, GMT", it is simply the number of seconds since that base date.
Dates by definition are location sensitive, as I write this my friend in the UK is already in tomorrow.
Day of week is calendar sensitive.
Thus the timezone and calendar need to be specified. In my case they seem to be correct by default but are best specified explicitly.
So, set the timezone:
- (void)setTimeZone:(NSTimeZone *)tz

What's your time zone? Chances are you are one day off because your time zone is sufficiently different from GST that the time you are representing is the next or previous day.
I have found it necessary to specify the date as being in the local time zone to avoid this.

Related

Convert timestamp into NSDate

I am parsing a JSON file which contains a timestamp. I want to convert this timestamp into an NSDate.
My code :
NSString *depart=[alternates valueForKey:#"startTime"];
NSTimeInterval intervaldep=[depart doubleValue];
NSDate *myDate = [NSDate dateWithTimeIntervalSince1970:intervaldep];
But I am getting wrong date, e.g.: 44135-04-01 03:20:00 +0000 for time stamp 1330606668000.
If any one has any idea please help.
Thank you.
Your timestamp contains milliseconds, just divide your timestamp by 1000 (i.e. trim the last three zeros) and you should be fine.
Try to add the NSTimeZone to your NSDate, by default the dates are in GMT0
You can check the syntax here:
Convert UTC NSDate to local Timezone Objective-C

Storing NSDate with system time zone in Core Data

When I store a date in CoreData as [NSDate date], it is saved -5:30 difference. In core data I used attribute type as date.
How to store NSdate with timeZone?
Update: Here is the code I am using:
To store the date:
database = (DataBase*) [fetchResults objectAtIndex:indexVal];
[database setDate:[NSDate date]];
NSError error = nil;
[managedObjectContext save:&error]
To retrieve the date:
DataBase *newDataBase = (DataBase) [fetchResults objectAtIndex:i];
NSDate *RetrivedDate = [newDataBase Date];
NSLog(#"Retrived Date :",RetrivedDate");
Before storing I log it. It shows current date and time. After storing I immediately fetched the date . but it showed 1 day delayed date..
NSDate doesn't have a time zone. It stores dates as a number of seconds since a reference date in GMT.
The time zone is applied when you format the date for display using NSDateFormatter. This will pick up the device time zone by default.

Extract date from UIDatePicker

Can u please tell me how to extract a date from UIDatePicker, i have extracted the month but i am not able to extract the date,Please help me out
Thank You
The NSDate object can be extracted by just accessing the date property of the object:
NSDate *dateFromPicker = [someDatePicker date];
If you want to extract detailed information about what month, day and year a person has chosen, this is a little bit more complex (but just a little bit). The solution is to use an NSCalendar reference - it is likely that you'd want to use Gregorian.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
Now you should use an unsigned integer unit flags to specify which units you want to extract from a date (i.e. day, day-of-the-month, year, era etc.). Use a bitwise | to select multiple unit flags:
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit;
Now create a date components object:
NSDateComponents *components = [calendar components: unitFlags fromDate: dateFromPicker];
From this components date, you can now extract integer values of what you have mentioned in the unitFlags integer:
int year = [components year];
int month = [components month];
All other properties (i.e. day, day-of-the-month, era etc.) are undefined in such a components object - remember, you can only extract what you've explicitly said you want to extract.
Finally, free the calendar object to avoid memory leaks:
[calendar release];
Hope this helps.
For more information, see Apple reference:
http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html
You can access the date property of the UIDatePicker class to get the date!

how to get a particular day of week in objective c?

Using the Gregorian calendar, I am able to get the number of the day of the week (i.e. 1 for Sunday and 2 for Monday, etc.) but I am not able to find a function that displays the name of week then the number. Can anyone help?
Here is my code to get the number of day:
NSDate *dates = [gregorian dateFromComponents:component];
NSDateComponents *weekdayComponents =[gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:dates];
NSUInteger *weekdays = [weekdayComponents weekday];
NSString *dayw=[NSString stringWithFormat:#"%1i",weekdays];
NSLog(#"%#",dayw);
Create an NSDateFormatter. The format string #"EEEE" will output the name of the day of the week.

How to check what day of the week it is (i.e. Tues, Fri?) and compare two NSDates?

I'm looking two do two things:
Check if a week has gone by (based on the day of the week)
Check if a day has gone by (based on the date)
I'm not sure what the best way to solve this is, since when comparing two NSDates (one at 1/1/09 at 21:30 and another at 1/2/09 at 00:30) I can't just see if 24 hours has gone by since in this case it hasn't. I can solve this by just getting the date 1/1/09 from the NSDate, but I'm unsure how to do this based on the documentation and google links that I saw.
For the other issue, I don't know how to know what day of the week it is given a date. I'd like to if 1/1/09 is a Tuesday, Monday, etc... Is there any library that let's you calculate this? This obviously needs to take into account leap years and a tons of other stuff... Maybe there's an objective-c library for this?
Thanks for any help!
You can use components:fromData: message of the NSCalendar class to get the individual date components:
// Sunday = 1, Saturday = 7
int weekday = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:theDate] weekday];
To compare two dates, just use the compare: message:
switch([date1 compare:date2])
{
case NSOrderedSame: /* they are the same date */ break;
case NSOrderedAscending: /* date1 precedes date2 */ break;
case NSOrderedDescending: /* date2 precedes date1 */ break;
}
You can use NSDateComponents for this:
unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:units fromDate:date];
then you can access individual parts of the date like this:
[components year];
[components month];
[components day];
Or, you can construct a new NSDate object using NSCalendar's dateFromComponents method, and compare the two NSDate objects.