I recently updated Xcode to version 6.0, and when I did so, I was warned that the NSDateComponents week method was deprecated, and the new weekOfYear method replaces it. I believe these methods should return the week ordinal of the year, between 1 and 52. But the value that I get with weekOfYear is way beyond 52.
The code that I used to test this is below. Can someone please verify this for me, and if I am doing something wrong, please tell me what that is?
- (void)testWeekOfYearMethod
{
NSLog(#"Inside testWeekOfYearMethod...");
NSDate *date = [NSDate date];
//NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendar *gregorian = [NSCalendar currentCalendar];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekCalendarUnit fromDate:date];
NSInteger weekOrdinal = [weekdayComponents weekOfYear];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd 'at' HH:mm"];
NSString *formattedString = [dateFormatter stringFromDate:date];
NSLog(#"In getWeekContainingDate(), Date: %# has week %ld", formattedString, [[NSNumber numberWithInteger:weekOrdinal] integerValue]);
}
weekOfYear is just a accessing the corresponding part of the NSDateComponents you have created. Your example does not specify the option NSWeekOfYearCalendarUnit, so it has nothing to access!
Add that to your options and you should get the result you are expecting:
NSDateComponents *weekdayComponents = [gregorian components:(NSWeekCalendarUnit | NSWeekOfYearCalendarUnit) fromDate:date];
Related
Following is my code to get current date.
-(NSString *) getCurrentDate {
NSDateFormatter *dateformater = [[NSDateFormatter alloc]init];
[dateformater setDateFormat:#"dd-MMM-yyyy"];
NSString *today=[dateformater stringFromDate:[NSDate date]];
return today;
}
Im using the following code to find the difference between current date and the date selected from pickerview
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MMM-yyyy"];
NSString *date = [dateFormat stringFromDate:picker.date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:GregorianCalendar];
NSCalendarUnit unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"dd-MMM-yyyy"];
NSDate *selectedDate = [f dateFromString:date];
NSDate *currentDate = [f dateFromString:[self getCurrentDate]];
NSDateComponents *currentDateComponent = [gregorianCalendar components:unitFlags fromDate:currentDate toDate:selectedDate options:0];
but the currentDateComponent.day always prints the value 10.
whats wrong with my code? how can i be able to find the difference between two dates?
I think components you are using is wrong it should but only NSCalendarUnitDay
My code is returning me correct difference (difference.day).
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *difference = [calendar components:NSCalendarUnitDay
fromDate:[NSDate date] toDate:enDate options:0];
Hello I am trying to add calendar events to iphone's calendar, but am unsure how to set a specific date and time. I have looked over the answer from here Programmatically add custom event in the iPhone Calendar
so I currently have:
Store.startDate = [NSDate Date] //this part is what I would like to set a specific year/month/day/hour/minutes at.
Any help would be greatly appreciated, Thanks.
Take a look here.
There's couple examples as well how to use NSDateComponents.
NSDateComponents *comps = [[NSDateComponents alloc] init];
// date
[comps setDay:10];
[comps setMonth:8];
[comps setYear:2015];
// time
[comps setHour:17];
[comps setMinute:13];
[comps setSecond:21];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
Get Current Date
NSLocale *en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
assert(en_US_POSIX != nil);
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:en_US_POSIX];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];
Get Current Time
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *dateComponents = [gregorian components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:now];
NSInteger hour = [dateComponents hour];
NSString *am_OR_pm=#"AM";
if (hour>12){
hour=hour%12;
am_OR_pm = #"PM";
}
NSInteger minute = [dateComponents minute];
NSString *strTime=[NSString stringWithFormat:#"%02d:%02d %#", hour, minute ,am_OR_pm];
This question already has an answer here:
NSDateFormatter - 1 day incorrect?
(1 answer)
Closed 7 years ago.
I try to get first date for the current month from [NSDate new]. My problem is that instead of 2015/06/01 I always receive 2015/05/31. I even try to convert string 20150601 to NSDate and I still receive 2015/05/31.
Here is my CODE (for the second element):
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyyMMdd"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
currentMonth = [dateFormatter dateFromString:#"20150601"];
The result is:
(lldb) print currentMonth
(__NSDate *) $0 = 0x79e64820 2015-05-31 21:00:00 UTC
EDIT:
Ok, I understand my mistake - I don't check correctly result of my operations. They always result in UTC.
10x, for answer and all comments. I will be more careful next time.
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:today];
components.day = 1;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSTimeZone *zone = [NSTimeZone localTimeZone];
[formatter setTimeZone:zone];
[formatter setDateFormat:#"yyyyMMdd"];
NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];
NSString *currentMonth = [formatter stringFromDate:dayOneInCurrentMonth];
NSLog(#"%#",currentMonth);
Output
2015-06-08 14:07:30.924 NSDATEDemo[1943:39838] 20150601
Create NSDateComponents from [NSDate date], set the current day to 1 and re-create your NSDate object:
- (NSDate *) dateAtStartOfMonth
{
//Not tested!!!
NSDateComponents *comp = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];
[comp setDay:1];
return [[NSCalendar currentCalendar] dateFromComponents:comp];
}
I want to get the current & next week dates with day name.
i.e. If today's date is 28-06-2013 (Friday) then I want to get the dates from 23-06-2013(sunday) to 29-06-2013 (Saturday) as the this current week.
for next week
I want to get dates from 30-06-2013(sunday) to 06-07-2013 (saturday).
How can I do this?
Thank you,
Here is sample code that does the trick.
-(NSArray*)daysThisWeek
{
return [self daysInWeek:0 fromDate:[NSDate date]];
}
-(NSArray*)daysNextWeek
{
return [self daysInWeek:1 fromDate:[NSDate date]];
}
-(NSArray*)daysInWeek:(int)weekOffset fromDate:(NSDate*)date
{
NSCalendar *calendar = [NSCalendar currentCalendar];
//ask for current week
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps=[calendar components:NSWeekCalendarUnit|NSYearCalendarUnit fromDate:date];
//create date on week start
NSDate* weekstart=[calendar dateFromComponents:comps];
if (weekOffset>0) {
NSDateComponents* moveWeeks=[[NSDateComponents alloc] init];
moveWeeks.week=1;
weekstart=[calendar dateByAddingComponents:moveWeeks toDate:weekstart options:0];
}
//add 7 days
NSMutableArray* week=[NSMutableArray arrayWithCapacity:7];
for (int i=1; i<=7; i++) {
NSDateComponents *compsToAdd = [[NSDateComponents alloc] init];
compsToAdd.day=i;
NSDate *nextDate = [calendar dateByAddingComponents:compsToAdd toDate:weekstart options:0];
[week addObject:nextDate];
}
return [NSArray arrayWithArray:week];
}
I was going to copy and paste an answer, but I'd suggest going and reading this post: Current Week Start and End Date. It looks like it'll help you achieve what you want to.
Something like this perhaps:
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger weekNumber = [[calendar components: NSWeekCalendarUnit fromDate:now] week];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [gregorian components:NSYearCalendarUnit fromDate:now];
[comp setWeek:weekNumber]; //Week number.
int i;
for (i = 1; i < 8; i=i+1){
[comp setWeekday:i]; //First day of the week. Change it to 7 to get the last date of the week
NSDate *resultDate = [gregorian dateFromComponents:comp];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEEE MMMM d, yyyy"];
NSString *myDateString = [formatter stringFromDate:resultDate];
NSLog(#"%#",myDateString);
}
Use NSDateComponents to find out the day of the week and then to find the date required before and after it.
Umm, I'm not an expert on this or anything, but a dumb way to do this is to first be able to recognize the day of the week from NSDate. Then you could add in if statements then the if statements could add and subtract the dates and nslog or printf each of them. Or I think there is a way by accessing the ios calendar.
okay so the above pretty much said and did more than what I said. Yeah go check the link on the post before me.
Use an NSCalendar instance to convert your start NSDate instance into an NSDateComponents instance, add 1 day to the NSDateComponents and use the NSCalendar to convert that back to an NSDate instance. Repeat the last two steps until you reach your end date.
NSDate *currentDate = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1];
NSDate *nextDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
Or else find start date and end date. like
NSDate *startDate = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:7];
NSDate *endDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
then,
NSDate nextDate;
for ( nextDate = startDate ; [nextDate compare:endDate] < 0 ; nextDate = [nextDate addTimeInterval:24*60*60] ) {
// use date
}
How can I have the title of UITableview with date?
I know I can edit the title using:
self.title=#"meals for ..";
I want to add the date for one week. How can I do that?
You can get a date like this:
NSDate *theDateToday = [NSDate date];
And format it like this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"EEE MMM dd"];
NSString *theDateAsAString = [dateFormatter stringFromDate:theDateToday];
Combine that with what you have like this:
self.title = [NSString stringWithFormat:#"meals for %#", theDateAsAString];
As for finding the days of the week, you could try adapting this answer.
- (NSString *)getWeekStartDateAsString:(NSDate *)date {
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
int dayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week
[components setDay:([components day] - ((dayofweek) - 2))];// for beginning of the week.
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:#"yyyy-MM-dd"];
dateString2Prev = [dateFormat stringFromDate:beginningOfWeek];
weekstartPrev = [[dateFormat_first dateFromString:dateString2Prev] retain];
return weekstartPrev;
}
- (NSString *)getWeekEndDateAsString:(NSDate *)date {
NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsEnd = [gregorianEnd components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
int Enddayofweek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today] weekday];// this will give you current day of week
[componentsEnd setDay:([componentsEnd day]+(7-Enddayofweek)+1)];// for end day of the week
NSDate *EndOfWeek = [gregorianEnd dateFromComponents:componentsEnd];
NSDateFormatter *dateFormat_End = [[NSDateFormatter alloc] init];
[dateFormat_End setDateFormat:#"yyyy-MM-dd"];
dateEndPrev = [dateFormat stringFromDate:EndOfWeek];
weekEndPrev = [[dateFormat_End dateFromString:dateEndPrev] retain];
return weekEndPrev;
}
You end result might look like this:
self.title = [NSString stringWithFormat:#"meals for %#-%#", [self getWeekStartDateAsString:theDateToday], [self getWeekEndDateAsString:theDateToday]];
A rarely known NSCalendar method will be the best option IMO
rangeOfUnit:startDate:interval:forDate:. It gives you the start and the duration (interval) for a certain time unit. With it it is easy to find the start of the week in the used calendar and add the range-1 to get the latest second in that week.
With the also rarely seen localizedStringFromDate:dateStyle:timeStyle: Available in OS X v10.6, iOS 4.0 it is easy to create a localized representation of the dates.
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDate *startOfTheWeek;
NSDate *endOfWeek;
NSTimeInterval interval;
[cal rangeOfUnit:NSWeekCalendarUnit
startDate:&startOfTheWeek
interval:&interval
forDate:now];
//startOfWeek is 2013-06-02 22:00:00 +0000 now (note: it is GMT with timezone support for my timezone Europe/Berlin/DST)
endOfWeek = [startOfTheWeek dateByAddingTimeInterval:interval-1];
// 2013-06-09 21:59:59 +0000
NSString *text = [NSDateFormatter localizedStringFromDate:startOfTheWeek
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterNoStyle];
text = [text stringByAppendingString:#" to "];
text = [text stringByAppendingFormat:#"%#", [NSDateFormatter localizedStringFromDate:endOfWeek
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterNoStyle]];
self.title=text;
results in 03.06.13 to 09.06.13 for my german locale, where Monday is start of the week.