iPhone NSDate eg. next Friday - objective-c

I want to create a function which results the date of next Friday but I have no plan how to do it. Has anyone a good hint to me ?

E.g. Get current date using NSDate, then use 'components>fromDate:' from NSCalendar to get the NSDateComponents, then add the time difference to next Friday and create a new NSDate and Bob's is your uncle.

Here is my working solution for getting the next 5 Sundays in Gregorian calendar:
self.nextBeginDates = [NSMutableArray array];
NSDateComponents *weekdayComponents = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int currentWeekday = [weekdayComponents weekday]; //[1;7] ... 1 is sunday, 7 is saturday in gregorian calendar
NSDateComponents *comp = [[NSDateComponents alloc] init];
[comp setDay:8 - currentWeekday]; // add some days so it will become sunday
// build weeks array
int weeksCount = 5;
for (int i = 0; i < weeksCount; i++) {
[comp setWeek:i]; // add weeks
[nextBeginDates addObject:[[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:[NSDate date] options:0]];
}
[comp release];

This should work
+ (NSDate *) dateForNextWeekday: (NSInteger)weekday {
NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit
fromDate:today];
/*
Add components to get to the weekday we want
*/
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
NSInteger dif = weekday-weekdayComponents.weekday;
if (dif<=0) dif += 7;
[componentsToSubtract setDay:dif];
NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract
toDate:today options:0];
return beginningOfWeek;
}

Keep it simple, safe, and readable! (....KISSAR?)
#define FRIDAY 6
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = 1;
NSDate *nextFriday = [NSDate date];
NSInteger iWeekday = [[gregorian components:NSWeekdayCalendarUnit fromDate:nextFriday] weekday];
while (iWeekday != FRIDAY) {
nextFriday = [gregorian dateByAddingComponents:dayComponent toDate:nextFriday options:0];
iWeekday = [[gregorian components:NSWeekdayCalendarUnit fromDate:nextFriday] weekday];
}
Now nextFriday has your date.
Hope this helps!
EDIT
Note that if the current date was already a Friday, it would return that instead of the next Friday. If that's undesirable just init your nextFriday to a day later (so if current date was a Friday, it would start on Saturday, forcing the next Friday. And if current date was a Thursday you'd automatically have your next Friday without needing the loop).

Here is my solution, and just to warn you, on a saturday is the friday before shown.
cheers to all
NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:today];
int weekday = [weekdayComponents weekday];
int iOffsetToFryday = -weekday + 6;
weekdayComponents.weekday = iOffsetToFryday;
NSDate *nextFriday = [[NSCalendar currentCalendar] dateByAddingComponents:weekdayComponents toDate:today options:0];

Related

Objective-C: find date given day of the year and year

I'm writing a GUI for a legacy data object where a date is saved in the integer properties day of the year and year (real "genius" design...)
How can I convert this data into day and month given the year?
I'm currently trying:
int theYear = 2016;
int theDayOfTheYear = 222;
NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:theYear];
[components setDay:theDayOfTheYear];
NSDate* theDate = [gregorian dateFromComponents:components];
This seems a bit too hacky to me. It could be just coincidence that it works with days >31 - haven't found any mention of this in the NSDateComponents class reference.
When I debug, po theDate gives me 2016-08-08 22:00:00 +0000
--> close, but it should be 2016-08-09 (!)
To perform the reverse operation, i.e. to convert a normal DD-MM-YYYY date into day of the year, I'm using this code:
NSDate *fullDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSYearCalendarUnit
forDate:fullDate];
But I can't seem to find the proper methods to do the opposite...
Sometimes a test is all takes :)
Don't forget that NSDate are GMT, so you might want to add [[NSTimeZone localTimeZone] secondsFromGMT] seconds to it.
It seems that you have it working :)
- (void) testDate
{
int startYear = 2016;
int startMonth = 1;
int startDay = 1;
// Create the startDate
NSDateComponents * startDateComp = [NSDateComponents new];
startDateComp.day = startDay;
startDateComp.month = startMonth;
startDateComp.year = startYear;
NSDate * startDate = [[NSCalendar currentCalendar] dateFromComponents:startDateComp];
for(int i=0 ; i < 365; i++)
{
// add i day to startDate
NSDate * testDate = [startDate dateByAddingTimeInterval:i * 24 * 60 * 60];
NSUInteger dayOfYear = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSYearCalendarUnit
forDate:testDate];
XCTAssert(dayOfYear == (i + 1), #"the day of the year should be i + 1");
// Create a date using day of year
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:startYear];
[components setDay:dayOfYear];
NSDate* resultDate = [[NSCalendar currentCalendar] dateFromComponents:components];
// testing result date against test date
NSInteger test, result;
test = [[NSCalendar currentCalendar] component:NSCalendarUnitDay fromDate:testDate];
result = [[NSCalendar currentCalendar] component:NSCalendarUnitDay fromDate:resultDate];
XCTAssert(test == result);
test = [[NSCalendar currentCalendar] component:NSCalendarUnitMonth fromDate:testDate];
result = [[NSCalendar currentCalendar] component:NSCalendarUnitMonth fromDate:resultDate];
XCTAssert(test == result);
test = [[NSCalendar currentCalendar] component:NSCalendarUnitYear fromDate:testDate];
result = [[NSCalendar currentCalendar] component:NSCalendarUnitYear fromDate:resultDate];
XCTAssert(test == result);
}
Please try this. Its the larger calendar unit NSCalendarUnitEra :)
NSDate *fullDate = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];
gregorian.timeZone = [NSTimeZone systemTimeZone];
NSUInteger dayOfYear = [gregorian ordinalityOfUnit:NSCalendarUnitDay
inUnit:NSCalendarUnitEra
forDate:fullDate];
NSDateComponents *dateCom = [[NSDateComponents alloc] init];
dateCom.day = dayOfYear;
NSDate *expectedDate = [gregorian dateFromComponents:dateCom];
NSLog(#"%#",expectedDate);

How to get the date of the weekends?

I would like to use the date of the weekends to use it in the NSLocalNotification, but i don't how to get it, i tried to do it mathematically, but sometimes i gets a number greater than the days of the month.
Note that iOS supports several Calendars, I am not sure, if all cultures that uses those calendars have a concept of weekends and if they are always meant to have two days.
Something you also needs to deal with: even in countries that uses the Gregorian calendar a week might start with monday or sunday.
But if we assume that a weekend are equivalent to saturday and sunday, this might be helpful for you:
NSDate *referenceDate = [NSDate date];
NSDate *startOfThisWeek;
NSDate *saturday;
NSUInteger backupStartWeekday = [[NSCalendar currentCalendar] firstWeekday];
[[NSCalendar currentCalendar] setFirstWeekday:1]; // ensure week begins at sunday
[[NSCalendar currentCalendar] rangeOfUnit:NSWeekCalendarUnit
startDate:&startOfThisWeek
interval:NULL
forDate:referenceDate];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSWeekdayCalendarUnit].length; //the start of the next week
components.day = components.day - 2;
saturday = [[NSCalendar currentCalendar] dateByAddingComponents:components
toDate:startOfThisWeek
options:0];
[[NSCalendar currentCalendar] setFirstWeekday:backupStartWeekday];
Your first problem about getting the date can be solved as :
NSCalendar *calender=[NSCalendar currentCalendar];
NSRange daysRange=[calender rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
NSUInteger numberOfDaysInMonth=daysRange.length;
//NSLog(#"num of days in current month : %ld",numberOfDaysInMonth);
NSDateComponents *dateComponents = [calender components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
NSInteger dayCount=[dateComponents weekday];
//if today itself is saturday what you want to display? today or upcoming one... then do small changes here, for sat & sun.
NSInteger daysForSaturday=7-dayCount;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd"];
NSUInteger todaysDate = [[formatter stringFromDate:[NSDate date]]integerValue];
// NSLog(#"Today is : %#",todaysDate);
NSUInteger comingSaturday=todaysDate+daysForSaturday;
if (comingSaturday>numberOfDaysInMonth) {
comingSaturday-=numberOfDaysInMonth;
}
NSUInteger comingSunday=comingSaturday+1;
NSLog(#"Coming.. Sat is : %ld, Sun in : %ld",comingSaturday, comingSunday);

How to get first day of the week in IOS [duplicate]

Does anyone know if there is a way to set the first day of the week on a NSCalendar, or is there a calendar that already has Monday as the first day of the week, instead of Sunday.
I'm currently working on an app that is based around a week's worth of work, and it needs to start on Monday, not Sunday. I can most likely do some work to work around this, but there will be a lot of corner cases. I'd prefer the platform do it for me.
Thanks in advance
Here's some the code that I'm using. it's saturday now, so what I would hope is that weekday would be 6, instead of 7. that would mean that Sunday would be 7 instead of rolling over to 0
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setFirstWeekday:0];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit;
NSDateComponents *todaysDate = [gregorian components:unitFlags fromDate:[NSDate date]];
int dayOfWeek = todaysDate.weekday;
Edit: This does not check the edge case where the beginning of the week starts in the prior month. Some updated code to cover this: https://stackoverflow.com/a/14688780/308315
In case anyone is still paying attention to this, you need to use
ordinalityOfUnit:inUnit:forDate:
and set firstWeekday to 2. (1 == Sunday and 7 == Saturday)
Here's the code:
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[gregorian setFirstWeekday:2]; // Sunday == 1, Saturday == 7
NSUInteger adjustedWeekdayOrdinal = [gregorian ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:[NSDate date]];
NSLog(#"Adjusted weekday ordinal: %d", adjustedWeekdayOrdinal);
Remember, the ordinals for weekdays start at 1 for the first day of the week, not zero.
Documentation link.
This code constructs a date that is set to Monday of the current week:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *today = [NSDate date];
NSDate *beginningOfWeek = nil;
BOOL ok = [gregorian rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek
interval:NULL forDate: today];
setFirstWeekday: on the NSCalendar object.
Sets the index of the first weekday for the receiver.
- (void)setFirstWeekday:(NSUInteger)weekday
Should do the trick.
In my opinion this settings should be dynamic according to the user locale.
Therefore one should use:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setLocale:[NSLocale currentLocale]];
This will cause the calendar to set the first week day according to the user locale automatically. Unless you are developing your app for a specific purpose/user locale (or prefer to allow the user to choose this day).
I've done it like this.
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *today = [NSDate date];
NSDateComponents *compForWeekday = [gregorian components:(NSWeekdayCalendarUnit) fromDate:today];
NSInteger weekDayAsNumber = [compForWeekday weekday]; // The week day as number but with sunday starting as 1
weekDayAsNumber = ((weekDayAsNumber + 5) % 7) + 1; // Transforming so that monday = 1 and sunday = 7
I had trouble with a lot of the answers here. . maybe it was just me. .
Here's an answer that works for me:
- (NSDate*)firstDayOfWeek
{
NSCalendar* cal = [[NSCalendar currentCalendar] copy];
[cal setFirstWeekday:2]; //Override locale to make week start on Monday
NSDate* startOfTheWeek;
NSTimeInterval interval;
[cal rangeOfUnit:NSWeekCalendarUnit startDate:&startOfTheWeek interval:&interval forDate:self];
return startOfTheWeek;
}
- (NSDate*)lastDayOfWeek
{
NSCalendar* cal = [[NSCalendar currentCalendar] copy];
[cal setFirstWeekday:2]; //Override locale to make week start on Monday
NSDate* startOfTheWeek;
NSTimeInterval interval;
[cal rangeOfUnit:NSWeekCalendarUnit startDate:&startOfTheWeek interval:&interval forDate:self];
return [startOfTheWeek dateByAddingTimeInterval:interval - 1];
}
Update:
As pointed out (elsewhere) by #vikingosegundo, in general its best to let the local determine which day is the start of the week, however in this case the OP was asking for the start of the week to occur on Monday, hence we copy the system calendar, and override the firstWeekDay.
The problem with Kris' answer is the edge case where the beginning of the week starts in the prior month. Here's some easier code and it also checks the edge case:
// Finds the date for the first day of the week
- (NSDate *)getFirstDayOfTheWeekFromDate:(NSDate *)givenDate
{
NSCalendar *calendar = [NSCalendar currentCalendar];
// Edge case where beginning of week starts in the prior month
NSDateComponents *edgeCase = [[NSDateComponents alloc] init];
[edgeCase setMonth:2];
[edgeCase setDay:1];
[edgeCase setYear:2013];
NSDate *edgeCaseDate = [calendar dateFromComponents:edgeCase];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:edgeCaseDate];
[components setWeekday:1]; // 1 == Sunday, 7 == Saturday
[components setWeek:[components week]];
NSLog(#"Edge case date is %# and beginning of that week is %#", edgeCaseDate , [calendar dateFromComponents:components]);
// Find Sunday for the given date
components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:givenDate];
[components setWeekday:1]; // 1 == Sunday, 7 == Saturday
[components setWeek:[components week]];
NSLog(#"Original date is %# and beginning of week is %#", givenDate , [calendar dateFromComponents:components]);
return [calendar dateFromComponents:components];
}
I see misunderstanding in the other messages. The first weekday, whichever it is, has number 1 not 0. By default Sunday=1 as in the "Introduction to Date and Time Programming Guide for Cocoa: Calendrical Calculations":
"The weekday value for Sunday in the Gregorian calendar is 1"
For the Monday as a first workday the only remedy I have is brute force condition to fix the calculation
NSCalendar *cal=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [cal components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
// set to 7 if it's Sunday otherwise decrease weekday number
NSInteger weekday=[comps weekday]==1?7:[comps weekday]-1;
Below also covers the edge case,
- (NSDate *)getFirstDayOfTheWeekFromDate:(NSDate *)givenDate
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:givenDate];
[components setWeekday:2]; // 1 == Sunday, 7 == Saturday
if([[calendar dateFromComponents:components] compare: curDate] == NSOrderedDescending) // if start is later in time than end
{
[components setWeek:[components week]-1];
}
return [calendar dateFromComponents:components];
}
You can just change .firstWeekday of the calendar.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
calendar.firstWeekday = 2;
Then use rangeOfUnit:startDate:interval:forDate: to get the first day
NSDate *startOfWeek;
[calendar rangeOfUnit:NSCalendarUnitWeekOfYear startDate:&startOfWeek interval:nil forDate:[NSdate date]];
Try this:
NSCalendar *yourCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]
[yourCal setFirstWeekday:0];
Iv found out the way to display any weekday name using nscalender..using the following code..
Just open your console from xcode menu bar to see the results.Copy Paste the following code in your viewDidLoad method to get the first day of the week
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy :EEEE"];
NSString *dateString = [dateFormat stringFromDate:today];
NSLog(#"date: %#", dateString);
[dateFormat release];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today];
[components setDay:([components day]-([components weekday]-1))];
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:#"MM/dd/yyyy :EEEE"];
NSString *dateString_first = [dateFormat_first stringFromDate:beginningOfWeek];
NSLog(#"First_date: %#", dateString_first);
The Output will be:
date: 02/11/2010 :Thursday
First_date: 02/07/2010 :Sunday
since i had run this program on 2/11/2010 u will get the desired output depending on the current date.
Similarly if u want to get the first working day of the week i.e Monday's date then just modify the code a bit:
CHANGE :[components setDay:([components day]-([components weekday]-1))];
TO
[components setDay:([components day]-([components weekday]-2))];
to get Mondays date for that week..
Similarly u can try to find the date of any of seven workdays by changing the integer -1,-2 and so on...
Hope u r question is answered..
Thanks,
Bonson Dias
The ISO 8601 calendar appears to have it's first weekday set to monday by default.
Using the Calendar nextWeekend (iOS 10 or later) and ordinality (thanks #kris-markel). I've gotten Monday as first of the week for the en_US calendar.
Here is an example of it with fallback to firstWeekday:
extension Calendar {
var firstWorkWeekday: Int {
guard #available(iOS 10.0, *) else{
return self.firstWeekday
}
guard let endOfWeekend = self.nextWeekend(startingAfter: Date())?.end else {
return self.firstWeekday
}
return self.ordinality(of: .weekday, in: .weekOfYear, for: endOfWeekend) ?? self.firstWeekday
}
}
The Swift solution (note, use .yearForWeekOfYear, not .year):
let now = Date()
let cal = Calendar.current
var weekComponents = cal.dateComponents([.yearForWeekOfYear, .weekOfYear,
.weekday], from: now)
//weekComponents.weekday = 1 // if your week starts on Sunday
weekComponents.weekday = 2 // if your week starts on Monday
cal.date(from: weekComponents) // returns date with first day of the week
… is there a calendar that already has Monday as the first day of the week, instead of Sunday.
Someday, there will be.
My simple way of doing this is to get Monday = 0, Sunday = 6:
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
NSInteger dayNumStartingFromMonday = ([dateComponents weekday] - 2 + 7) % 7; //normal: Sunday is 1, Monday is 2

Comparing the time of two NSDates, ignoring the date component

I want to compare two NSDates with NOW ([NSDate date]).
NSDate *date1 = [NSDate dateWithString:#"1982-02-12 07:00:00 +0100"];
NSDate *now = [NSDate dateWithString:#"2012-01-25 10:19:00 +0100"]; //example
NSDate *date2 = [NSDate dateWithString:#"1989-02-12 15:00:00 +0100"];
I would like to check if now is between date1 and date2. In the example above this is the case. The date component should be completely ignored, so only the time component should be compared. How could I accomplish this?
Thanks in advance!
unsigned int flags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date1];
NSDate* timeOnly = [calendar dateFromComponents:components];
This will give you a date object where everything but the hours/minutes/seconds have been reset to some common value. Then you can use the standard NSDate compare functions on them.
For reference, here is the opposite question to yours: Comparing two NSDates and ignoring the time component
You can create a date representing the start of today and add the time as components to it to get the boundary dates.
NSDate *now = [NSDate date];
NSDate *startOfToday;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&startOfToday interval:NULL forDate:now];
NSDateComponents *startComps = [[NSDateComponents alloc] init];
startComps.hour = 7;
startComps.minute = 30;
NSDateComponents *endComps = [[NSDateComponents alloc] init];
endComps.hour = 20;
NSDate *startDate = [[NSCalendar currentCalendar] dateByAddingComponents:startComps toDate:startOfToday options:0];
NSDate *endDate = [[NSCalendar currentCalendar] dateByAddingComponents:endComps toDate:startOfToday options:0];
if ([startDate timeIntervalSince1970] < [now timeIntervalSince1970] && [now timeIntervalSince1970] < [endDate timeIntervalSince1970]) {
NSLog(#"good");
}
NSDateFormatter* formatterDate = [[[NSDateFormatter alloc] init] autorelease];
formatterDate.dateStyle = NSDateFormatterMediumStyle; // whatever format you like
NSDate *first_Date = [formatterDate dateFromString:#""];
NSDate *second_Date = [formatterDate dateFromString:#""];
NSDate *todaysDate = [NSDate date];
NSTimeInterval timeIntFormFirstDate = [todaysDate timeIntervalSinceDate:First_Date];
NSTimeInterval timeIntFronLastDate = [second_Date timeIntervalSinceDate:todaysDate];
int interval1 = timeIntFormFirstDate/60;
int interval2 = timeIntFronLastDate/60;
if (interval1 >0 && interval2 >0)
{
NSLog(#"Today's date is between first and second date");
}

How to set time on NSDate?

I want to set the NSDate time with my desired hours:minutes:seconds
currently im working with NSDate component but it is not giving the desired result
[comps setHour: -hours];
[comps setMinute:0];
[comps setSecond:0];
NSDate *minDate = [calendar_c dateFromComponents:comps];
This works great as an NSDate category.
/** Returns a new NSDate object with the time set to the indicated hour,
* minute, and second.
* #param hour The hour to use in the new date.
* #param minute The number of minutes to use in the new date.
* #param second The number of seconds to use in the new date.
*/
-(NSDate *) dateWithHour:(NSInteger)hour
minute:(NSInteger)minute
second:(NSInteger)second
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: NSYearCalendarUnit|
NSMonthCalendarUnit|
NSDayCalendarUnit
fromDate:self];
[components setHour:hour];
[components setMinute:minute];
[components setSecond:second];
NSDate *newDate = [calendar dateFromComponents:components];
return newDate;
}
With the above category, if you have an existing date you want to change the time on, you do so like this:
NSDate *newDate = [someDate dateWithHour:10 minute:30 second:00];
If, however, you are trying to add or subtract hours from an existing date, a category method to do that is also straightforward:
/** Returns a new date with the given number of hours added or subtracted.
* #param hours The number of hours to add or subtract from the date.
*/
-(NSDate*)dateByAddingHours:(NSInteger)hours
{
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:hours];
return [[NSCalendar currentCalendar]
dateByAddingComponents:components toDate:self options:0];
}
Your approach should work fine. I needed a solution for this type problem (setting the individual date components) and the following code works as expected for me. My situation: I wanted to create a date object that used the current date but had the time set to a value that was passed in as a string.
NSString *string = #"7:00";
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
NSDateFormatter *timeOnlyFormatter = [[NSDateFormatter alloc] init];
[timeOnlyFormatter setLocale:locale];
[timeOnlyFormatter setDateFormat:#"h:mm"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *today = [NSDate date];
NSDateComponents *todayComps = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:today];
NSDateComponents *comps = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[timeOnlyFormatter dateFromString:string]];
comps.day = todayComps.day;
comps.month = todayComps.month;
comps.year = todayComps.year;
NSDate *date = [calendar dateFromComponents:comps];
[calendar release];
[timeOnlyFormatter release];
[locale release];
One thing to note is that you really have to pay attention to time zones when you are judging whether a time appears to be accurate. For example, in my app, when you stop at a breakpoint, you will see the time in GMT (so it looks different than the input time, which is in my local time), but when the time is actually displayed on screen in the app, it is being formatted to display in the local timezone. You may need to take this into consideration to determine whether the result is actually different from what you would expect.
If this does not help, can you elaborate on "not giving the desired result"? What result is it giving and how does that compare to what you expected?
is Swift2
extension NSDate {
func dateWithHour (hour: Int, minute:Int, second:Int) ->NSDate?{
let calendar = NSCalendar.currentCalendar(),
components = calendar.components([.Day,.Month,.Year], fromDate: self)
components.hour = hour;
components.minute = minute;
components.second = second;
return calendar.dateFromComponents(components)
}
}
You can set 0 to hour, min, and second.
NSDateFormatter *tFmt = [[NSDateFormatter alloc] init];
tFmt.dateFormat = #"yyyy-MM-dd";
NSString *strNowDate = [NSString stringWithFormat:#"%# 00:00:00",[tFmt stringFromDate:[NSDate date]]];
NSDate *nowDate = [NSDate dateWithString:strNowDate formatString:#"yyyy-MM-dd HH:mm:ss"];
Swift 5 solution (based on #dattk answer) for those who fear Deprecation warnings :)
func date(withHour hour: Int, withMinute minute: Int, withSeconds second: Int) -> Date? {
let now = Date()
let calendar = NSCalendar.current
var components = calendar.dateComponents([.day,.month,.year], from: now)
components.hour = hour
components.minute = minute
components.second = second
return calendar.date(from: components)
}
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:[NSDate date]];
comps.hour = 0;
comps.minute = 15;
NSDate *date = [calendar dateFromComponents:comps];
iOS 8