Get first day in a month from NSCalendar - cocoa

I have this subset of a method that needs to get day one of the current month.
NSDate *today = [NSDate date]; // returns correctly 28 february 2013
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *dayOneInCurrentMonth = [gregorian dateByAddingComponents:components toDate:today options:0];
dayOneInCurrentMonth then prints out 2013-03-01 09:53:49 +0000, the first day of the next month.
How do I get day one of the current month?

Your logic is wrong: Instead of setting the date's day to 1, you're adding a day to the current date.
Try something like that:
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:today];
components.day = 1;
NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];

You want [NSCalender dateFromComponents:] instead:
NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];

Easy way of getting to the 1st from a given date:
NSDate *first = [gregorian dateBySettingUnit:NSCalendarUnitDay value:1 ofDate:date options:0];

Easy Way to get first and last date of previous month is :
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comp = [gregorian components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ) fromDate:[NSDate date]];
//TO GET PREVIOUS MONTH LAST DAY
[comp setMonth:[comp month]];
[comp setDay:1];
NSDate *tDateMonth = [gregorian dateFromComponents:comp];
NSLog(#"LAST DAY OF PREVIOUS MONTH ; %#", tDateMonth);
//TO GET PREVIOUS MONTH FIRST DAY
[comp setMonth:[comp month]-1];
[comp setDay:3];
NSDate *td = [gregorian dateFromComponents:comp];
NSLog(#"FIRST DAY OF PREVIOUS MONTH ; %#", td);
Hope this helps

By creating new variable is expensive on memory usage, it's better using date formatter to get the first day of the current month
today = [NSDate date];
firstDayDateFormatter = [[NSDateFormatter alloc] init];
[firstDayDateFormatter setDateFormat:#"01-MM-yyyy"];
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:#"en_US"]];
firstDayOfTheMonth = [mdfDateFormat dateFromString:[firstDayDateFormatter stringFromDate:today]];

NSDate *startDate = nil;
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitMonth startDate:&startDate interval:NULL forDate:date];
return startDate;

Related

How to get current time along with the Timezone in XCode?

I tried this :
NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YYYY-MM-dd hh:mm:ss TZD"];
NSString *dateString = [dateFormat stringFromDate:date];
NSLog(#"Current Date : %#",dateString);
and the result I get is Date and Time but not the Timezone.
#Vaibhav you have to use time zone like this
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
refer this link
Get the time and date of selected time zone?

NSDate hours are not correct after constructing date from components

I'm trying to construct a date from two different dates. When I break down both dates into their respective components and re-assemble them into the new date.. everything seems to be correct except the hours. Im sure its something simple that has to do with the timezone or the NSGregorianCalendar, but I am new to iOS, and programming NSCalendar. Im hoping someone will catch the simple mistake Im making.
//grab today's date so we can brek it down into components
NSDate *todayDate = [NSDate date];
NSLog(#"Todays Date: %#", todayDate);
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
//break down the stored date into components
NSDateComponents *theTime = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:storedIncorrectDate];
NSLog(#"Incorrect Calendar Components %#", theTime);
NSDateComponents *todayCalendarComponents = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:todayDate];
NSInteger currentYear = [todayCalendarComponents year];
NSLog(#"The Year: %i", currentYear);
NSInteger currentMonth = [todayCalendarComponents month];
NSLog(#"The Month: %i", currentMonth);
NSInteger currentDay = [todayCalendarComponents day];
NSLog(#"The Day: %i", currentDay);
NSLog(#"Today's Calendar Components %#", todayCalendarComponents);
NSInteger theHours = [theTime hour];
NSLog(#"Hours: %i", theHours);
NSInteger theMinutes = [theTime minute];
NSLog(#"Minutes: %i", theMinutes);
NSInteger theSeconds = [theTime second];
NSLog(#"Seconds: %i", theSeconds);
//build my new date and store it before we play the affirmation.
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:theHours];
[components setMinute:theMinutes];
[components setSecond:theSeconds];
[components setYear:currentYear];
[components setMonth:currentMonth];
[components setDay:currentDay];
[components setTimeZone:[NSTimeZone localTimeZone]];
NSLog(#"The Components: %#", components);
NSCalendar *updatedCal = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *revisedCorrectedDate = [updatedCal dateFromComponents:components];
NSLog(#"The Hours: %i", theHours);
NSLog(#"The New and Corrected Date: %#", revisedCorrectedDate);
The result of the log printing the revisedCorrectedDate shows everything correct that I set except the hours. This has to be a simple fix.. I just don't see it. Thank you in advance!
Are you sure it's incorrect? When I run this code, I get:
2012-06-03 18:13:36.130 Untitled[39805:707] The New and Corrected
Date: 2012-06-04 01:13:36 +0000
It's currently 6/3/12 18:13:36 here, and the date displayed is 6/4/12 01:13:36, which is the correct time, in UTC (notice the +0000 at the end).

Set the time of the DatePicker

How do I set the time of the DatePicker at 00:00:00 of the current date?
- (void) awakeFromNib
{
[datePicker setDateValue:[NSDate date]];
NSDate *now = [NSDate date];
int daysToAdd = 364;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
[datePicker1 setDateValue:newDate1];
}
cringe
It looks like you have two different datePickers? datePicker and datePicker1? What's up with that?
Also, this does not do what you're expecting:
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*364];
That is creating a new date that is exactly 31,449,600 seconds in the future. It is not doing anything other than that.
What you want to do is extract all of the date components from the current date and zero them out:
NSDate *now = [NSDate date];
NSDateComponents *nowComponents = [[NSCalendar currentCalendar] components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:now];
// technically these next lines are unnecessary, since we only pulled out the era-year-month-day, but they're included here for understanding/completeness:
[nowComponents setHour:0];
[nowComponents setMinute:0];
[nowComponents setSecond:0];
// now we can turn it back into a date:
NSDate *todayAtMidnight = [[NSCalendar currentCalendar] dateFromComponents:nowComponents];

Interval between 2 NSDates

I am trying to calculate an interval between now and a user defined date in days so that the results appear in a label on tapping a button.
The difference is always -4080 I am not sure what is wrong with my equation.
Thank you for your help
- (void)LabelChange2:(id)sender{
NSDateFormatter *df3 = [[NSDateFormatter alloc] init];
df3.dateStyle = NSDateFormatterMediumStyle;
labelDOB.text = [NSString stringWithFormat:#"%#",
[df3 stringFromDate:datepick.date]];
}
NSDate * df3 = [datePick date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components: NSDayCalendarUnit
fromDate: [NSDate date]
toDate: df3
options: 0];
int days = [comps day];
labelResult.text = [NSString stringWithFormat:#"%i", days];
Your code works fine. However if I run the code with the datePick pointer set to nil I will get an answer of -4080 from this code. You should check your connections to the UIDatePicker.

How to create a specific date in the distant past, the BC era

I’m trying to create a date in the BC era, but failing pretty hard. The following returns ‘4713’ as the year, instead of ‘-4712’:
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [NSDateComponents new];
[components setYear: -4712];
NSDate *date = [calendar dateFromComponents:components];
NSLog(#"%d", [[calendar components:NSYearCalendarUnit fromDate: date] year]);
Any idea what I’m doing wrong?
UPDATE: Working code
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [NSDateComponents new];
[components setYear: -4712];
NSDate *date = [calendar dateFromComponents:components];
NSDateComponents *newComponents = [calendar components:NSEraCalendarUnit|NSYearCalendarUnit fromDate:date];
NSLog(#"Era: %d, year %d", [newComponents era], [newComponents year]);
This prints 0 for the era, just as Ben explained.
Your code is actually working fine. Since there’s no year zero, -4712 is the year 4713 BC. If you check the era component you’ll see that it’s zero, which in the Gregorian calendar indicates BC. Flip that negative sign and you’ll see 4712 AD (era 1).

Resources