iPhone - adjusting the date on a UIDatePicker - iphone

I have the hour and the minute as NSIntegers (I don't care about the seconds... it may be 00) and I have a UIDatePicker adjusted to display just time (UIDatePickerModeTime).
Simple question: how do I set an hour on the UIDatePicker? Hours are in the 24h format (as it comes from the picker naturally).
Suppose this:
NSInteger hour = 17;
NSInteger minute = 12;
[myTimePicker setDate: ????];
I know I have to convert that hour and minute to NSDate, but how do I do that without including a day? I just need time.
I have read this example, but it also considers the day.
How do I construct a NSDate of just time, so I can adjust my UIDatePicker?
thanks

You should be able to do this,
NSCalendar * gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents * dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setHour:17];
[dateComponents setMinute:12];
myTimePicker.date = [gregorian dateFromComponents:dateComponents];
You can later get the hour and minute like this,
NSCalendar * gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents * dateComponents = [gregorian components:(NSHourCalendarUnit|NSMinuteCalendarUnit) fromDate:myTimePicker.date];
int hour = [dateComponents hour];
int minute = [dateComponents minute];

Related

Get first and last day of week for a couple of weeks

I need to make a calendar in which the user can scroll between several weeks. The first and last day of the week will be displayed like (e.g.) "June 4 - June 10".
Now I knew from the beginning that I'd need NSDate and NSCalendar, and indeed I managed to get the first and last day of just thist week, but it looks extremely cumbersome and I am sure there needs to be an easier method, as I need to get the dates for several more coming and past weeks.
This is my code which gives the day and month of the first and last day of the current week:
NSDate *today = [NSDate date];
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comp = [cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSYearCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit) fromDate:[NSDate date]];
NSDate *beginOfWeek = [today dateByAddingTimeInterval: -1*([comp weekday]-2)*24*3600];
NSDate *endOfWeek = [today dateByAddingTimeInterval:(7-[comp weekday]+2)*24*3600];
NSLog(#"beginWeekDay=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: beginOfWeek] day]);
NSLog(#"endWeekDay=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: endOfWeek] day]);
NSLog(#"beginWeekmonth=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: beginOfWeek] month]);
NSLog(#"endWeekmonth=%d\n",[[cal components:(NSWeekdayCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit) fromDate: endOfWeek] month]);
I found this, which may be helpful to you: http://www.cocoanetics.com/2009/11/add-one-week-skip-weekend/
- (NSDate *)addWeekToDateAndSkipWeekend:(NSDate *)now {
int daysToAdd = 6; // we'll add the 7th later
// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd];
// create a calendar
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *newDate = [gregorian dateByAddingComponents:components toDate:now options:0];
[components setDay:1]; // reuse to skip single days
NSDateComponents *newDateComps; // new componets to get weekday
// do always executed once, so we add the 7th day here
do
{
// add one day
newDate = [gregorian dateByAddingComponents:components toDate:newDate options:0];
newDateComps = [gregorian components:NSWeekdayCalendarUnit fromDate:newDate];
// repeat if the date is Saturday (7) or Sunday (1)
NSLog(#"weekday: %d", [newDateComps weekday]);
} while (([newDateComps weekday]==7)||([newDateComps weekday]==1));
return newDate;
}
Theoretically, you run this in a for loop with [NSDate date] and you will get the 7th day returned, you would then run the returned 7th day through this and get the next..etc..
May need minor alteration, to remove the check for Saturday+Sunday if you don't need it.
Hope this helps !

How to parse and extract Year, Month, Day etc from time interval on iphone IOS

I am slowly getting into iOS development and trying to create a count up timer from a specific date. I have figured out the code which gives me the interval in seconds but I could not figure out how to extract Year/Month/Day/Hour/Minute/Second values from it in order to display each value in its own label as a ticker.
So far I have figured out that the following will give me the interval between the 2 dates in seconds, what I am trying to do is to parse this and display on my view this as a ticker by updating the UILabel every second using NSTimer and calling selector once every 1 seconds and get something like this on my view:
6Years 10Months 13Days 18Hours 25Minutes 18Seconds (obviously each label will be updated accordingly as the time goes up)
NSDate *startDate = [df dateFromString:#"2005-01-01"];
NSTimeInterval passed = [[NSDate date] timeIntervalSinceDate: startDate];
Thanks
Use NSCalendar with the two dates:
- (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts
Returns, as an NSDateComponents object using specified components, the difference between two supplied dates.
Example:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY-MM-dd"];
NSDate *startingDate = [dateFormatter dateFromString:#"2005-01-01"];
NSDate *endingDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0];
NSInteger days = [dateComponents day];
NSInteger months = [dateComponents month];
NSInteger years = [dateComponents year];
NSInteger hours = [dateComponents hour];
NSInteger minutes = [dateComponents minute];
NSInteger seconds = [dateComponents second];
NSLog(#"%dYears %dMonths %dDays %dHours %dMinutes %dSeconds", days, months, years, hours, minutes, seconds);
NSLog output:
13Years 10Months 6Days 8Hours 6Minutes 7Seconds
Well, as "month" and "year" will of course depend on which month and which year it is (365 or 364 days in a year? 30 or 31 days in a month?), you cannot just take the time interval and extract years and months - you always have to get a full date, e.g. by adding your (modified) time interval back to the start date like
NSDate* newDate = [startDate dateByAddingTimeInterval:modifiedPassedTimeInterval];
From that date, you can easily extratc the year, month, and so on with NSDateComponents:
NSDateComponents* dateComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:newDate];
NSInteger day = [dateComponents day];
NSInteger month = [dateComponents month];
NSInteger year = [dateComponents year];

How can we get Next Date From Entered Date based on given repeate period ?

I am new to iPhone.
I want to find out the next date from given date based on repeat period.
For example :
I want function as follows ...
given date : 31'May 2011 and Repeat : Monthly given as argument then the next date should be returned 31'July 2011 (as June don't have 31st day)
And function should be smart enough to to calculate next leap year day also, if given date : 29'Feb 2008 and Repeat : Yearly given as argument then the next date should be returned 29'Feb 2012 (The next leap year day)
And so on repeat option can be one of these : Daily, Weekly(On selected day of week), Monthly, Yearly, None(No repeat at all)
// start by retrieving day, weekday, month and year components for yourDate
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todayComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) yourDate];
NSInteger theDay = [todayComponents day];
NSInteger theMonth = [todayComponents month];
NSInteger theYear = [todayComponents year];
// now build a NSDate object for yourDate using these components
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:theDay];
[components setMonth:theMonth];
[components setYear:theYear];
NSDate *thisDate = [gregorian dateFromComponents:components];
[components release];
// now build a NSDate object for the next day
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate: yourDate options:0];
[offsetComponents release];
[gregorian release];
This is copied from How can i get next date using NSDate? and the credit goes to #Massimo Cafaro for this answer.
To get tomorrow's date use the dateByAddingTimeInterval method.
// Start with today
NSDate *today = [NSDate date];
// Add on the number of seconds in a day
NSTimeInterval oneDay = 60 * 60 * 24;
NSDate *tomorrow = [today dateByAddingTimeInterval:oneDay];
It's pretty simple to extend that to a week etc
NSTimeInterval oneWeek = oneDay * 7;
NSDate *nextWeek = [today dateByAddingTimeInterval:oneWeek];
try this :-
- (NSDate *)dateFromDaysOffset:(NSInteger)daysOffset
{
// start by retrieving day, weekday, month and year components for yourDate
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:daysOffset];
NSDate *offsetDate = [gregorian dateByAddingComponents:offsetComponents toDate:self options:0];
[offsetComponents release];
[gregorian release];
return offsetDate;
}

iPhone NSDate question

I am trying to work through some of the AppsAmuck tutorials but they mostly seem to use code that Apple has deprecated. For example, there is a function that is called by a timer every second that looks like this:
NSDate *now = [NSDate date];
int hour = 23 - [[now dateWithCalendarFormat:nil timeZone:nil] hourOfDay];
int min = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] minuteOfHour];
int sec = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] secondOfMinute];
countdownLabel.text = [NSString stringWithFormat:#"%02d:%02d:%02d", hour, min,sec];
Unfortunately, none of this works with today's current SDK. I have been staring glossy-eyed at Apple's NSDate documentation and I am having trouble translating the intent of the function above into current day NSDate lingo.
This is what I use...but there are other methods
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
[gregorian release];
Returns the hour, minute and second from the current

Iphone SDK: How to Countdown from current time to a specific day in the future

I have was wondering how it would be possible to show the specific time remaining for a date in the future.
This is what i have so far. I can get the current time, and display that, and i used the minutes to midnight tutorial to figure out how to find out what time it will be midnight. But i am suck as to finding out how i would pick a day in the future and find out how much time is left there.
code:
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now];
NSInteger hour = 23 - [dateComponents hour];
NSInteger minute = 59 - [dateComponents minute];
NSInteger second = 59 - [dateComponents second];
[gregorian release];
countdownLabel.text = [NSString stringWithFormat:#"%02d:%02d:%02d", hour, minute, second];
Any possibility someone could take a look at this and change it up a bit? It would be easiest for me to follow if i could understand it from using some of this code, but if thats not possible or correct I would rather know the right way to do it.
Thanks.
Try one of these, it will be number of second between the two dates in double:
NSTimeInterval timeBetweenThenAndNow = [futureDate timeIntervalSinceNow];
NSTimeInterval timeBetweenThenAndMidnight = [futureDate timeIntervalSinceDate: myMidnightDate];