First of all: I want to say happy new year to everybody reading this!! May 2015 be a great year for all of us :-).
I'm busy with making a function which calculates the time difference between two dates. To be more precise: the time between a time and date given and the current time and date.
So the user selects a date in the past and then the program shows the time difference between the given date and todays date in a timer like so: "hh:mm:ss"
It works okay and updates every second when i select a time of todays date (01-01-2015 10:00:00), but when selecting a date and time in the past (31-12-2014 17:00:00) and compare it to todays date where the time is earlier than yesterday (01-01-2015 14:01:01), it gives me a negative time like a sort of countdown timer: -2:-59:-59.
But i want it to show the opposite of it: 21:01:01 and if possible if it exceeds the 24:00:00, just count on. For example 25:12:39.
This is the code that calculates the difference:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd-MM-YYYY HH:mm:ss"];
NSDate *date1 = [df dateFromString:[NSString stringWithFormat:#"30-12-2014 %#", startedTime]];
NSDate *date2 = [df dateFromString:[NSString stringWithFormat:#"31-12-2014 %#", [self getCurrentTime]]];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
int hours = (int)interval / 3600; // integer division to get the hours part
int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
int seconds = (interval - (hours*3600) - (minutes*60)); // interval minus hours part (in seconds) divided by 60 yields minutes
NSString *timeDiff = [NSString stringWithFormat:#"%02d:%02d:%02d", hours, minutes, seconds];
_workingTime.text = [NSString stringWithFormat:#"%#",timeDiff];
Can someone please help?
[df setDateFormat:#"dd-MM-yyyy hh:mm:ss"];
Try after this change of the format string!
And this.. finally.
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
if( interval < 0 ) {
interval = [date1 timeIntervalSinceDate:date2];
}
More about date formats here
Related
This should be simple, but it's proving challenging for me. I'd like to know the best approach to calculating the difference in seconds between [NSDate date] and a future event x seconds from that time. There are several different types of event, and each event may occur several times a day, and at different times, depending what day of the week it happens to be.
What I am trying to do is have the user select an event type from a picker and then set an alarm in Notification Center for the next occurrence of that event based on their selection. I have everything working fine, except for the seconds calculation.
So, for example, let's say it's 9am on a Monday. I'd like to determine how many seconds it would be between now and a user selected event that regularly occurs every Tuesday, Thursday, and Saturday at 10am, 4pm, and 11pm on each day, or on Sunday at 1pm. How would you approach this most efficiently?
When you're talking about a time or date like "next Thursday at 1 PM", that's information that only makes sense in the context of a calendar. NSDate is not going to provide you with much help. It would perhaps be more appropriately named NSPointInTime. It's just a number of seconds that have passed from some earlier, arbitrary reference point in time. It has no notion of weekdays, ante/post meridiem, or even hour of the day.
The two objects that do know about those sorts of thing are NSDateComponents and NSCalendar. Working together, they can create an NSDate from a specification like "next Thursday at 1PM".
You can decompose any date into components using -[NSCalendar components:fromDate:], and you can then use other NSDateComponents objects to perform arithmetic on the individual pieces of information. Find the weekday of today, for example, and its difference from Thursday. Then use -[NSCalendar dateByAddingComponents:toDate:options:] to create a new date based on that offset.
#interface NSCalendar (NextWeekday)
- (NSInteger)maxWeekday;
- (NSDate *)dateFromComponents:(NSDateComponents *)comps
forNextWeekday:(NSInteger)weekday
atHour:(NSInteger)hour;
#end
#implementation NSCalendar (NextWeekday)
- (NSInteger)maxWeekday
{
return [self maximumRangeOfUnit:NSWeekdayCalendarUnit].length;
}
- (NSDate *)dateFromComponents:(NSDateComponents *)comps
forNextWeekday:(NSInteger)weekday
atHour:(NSInteger)hour
{
NSInteger diff = weekday - [comps weekday];
if( diff < 0 ){
diff += [self maxWeekday];
}
NSDateComponents * weekdayOffset = [NSDateComponents new];
[weekdayOffset setWeekday:diff];
[comps setHour:hour];
return [self dateByAddingComponents:weekdayOffset
toDate:[self dateFromComponents:comps]
options:0];
}
#end
#define GREGORIAN_THURSDAY 5
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSCalendar * cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents * wednesday = [NSDateComponents new];
[wednesday setDay:3];
[wednesday setWeekday:4];
[wednesday setMonth:6];
[wednesday setYear:2013];
NSDateComponents * friday = [NSDateComponents new];
[friday setDay:5];
[friday setWeekday:6];
[friday setMonth:6];
[friday setYear:2013];
NSDateComponents * now = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit
fromDate:[NSDate date]];
NSDateComponents * lastSatOfDecember = [NSDateComponents new];
[lastSatOfDecember setDay:29];
[lastSatOfDecember setWeekday:7];
[lastSatOfDecember setMonth:12];
[lastSatOfDecember setYear:2012];
NSLog(#"From Wednesday: %#", [cal dateFromComponents:wednesday
forNextWeekday:GREGORIAN_THURSDAY
atHour:13]);
NSLog(#"From Friday: %#", [cal dateFromComponents:friday
forNextWeekday:GREGORIAN_THURSDAY
atHour:13]);
NSLog(#"From now: %#", [cal dateFromComponents:now
forNextWeekday:GREGORIAN_THURSDAY
atHour:13]);
NSLog(#"Crossing over the year: %#", [cal dateFromComponents:lastSatOfDecember
forNextWeekday:GREGORIAN_THURSDAY
atHour:13]);
}
return 0;
}
I'm current piecing together a streaming radio app for a show I work on and so far, it's okay - the streaming works once you push the 'Listen Live!' button and since that's the main aim, I'm happy. However, I'm trying to get clever now and set up an on-screen display that shows when the show is on the air; it's only on for two hours a week, so I thought it'd be nice to show when it's on and off via an on-screen display in the app. Nothing fancy... here's what I've got on screen so far:
1) A counting clock taken from here - EDIT: http://www.youtube.com/watch?v=pNVWST15pyc – that's really simple. Can't believe I didn't realise that changing the hh to HH makes it 24-hour... god, I'm so dumb.
2) A label to show just the day of the week, not the date or month, taken from here - NSCalendar to Display Weekday - as the app only needs to know whether it's Sunday (the on-air day) or not. EDIT: Made this work properly now because I'm an idiot who didn't link it up properly. :(
What I really want to do, however, is have the app set up two settings for an image view - an 'on air' and 'off air' switch - so that when it's between 8pm and 10pm on Sunday night, it shows the 'on air' image and when it's any other time, it shows the 'off air' one. I'm pretty sure that's an if statement but I'm not sure where to start trying to combine the clock and weekday bits to make that work. Can anyone make some suggestions please?
Also, since those times are GMT, I want to lock the app into GMT regardless of where in the world the user is so it relates directly to the show. I'm guessing I can do that using the timeZone:nil bit of the clock code by changing the 'nil' bit to 'Europe/London', but doing so just makes the whole thing crash out in spectacular fashion (I've tried it in various forms with no success). Again, suggestions would be massively appreciated.
Apologies for asking what may seem like simple questions - aside from some adult learning courses on Xcode, I'm a bit of a novice. :D
You should use the NSDateComponents object, which has a -weekday instance method (1 being Sunday for the gregorian calendar). Details on how to get started are in Apple's Date and Time Programming Guide. Here's a code sample that relates to what you are trying to do:
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
[gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
NSInteger day = [weekdayComponents day];
NSInteger weekday = [weekdayComponents weekday];
NSDateComponents will also let you get and set (through so-called accessor methods) hour, minute, second, and timezone.
For the problem you described above, I would write a method like this:
- (BOOL)isShowOnAir {
BOOL onAir = NO;
NSDate *now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSTimeZoneCalendarUnit) fromDate:now];
[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSInteger day = [components day]; // Sunday == 1
if (day == 1) {
NSInteger hour = [components hour];
//NSInteger minute = [components minute]; -- not used but here's how to access it
if (hour == 20 || hour == 21) { // covers 8:00 - 9:59 PM
onAir = YES;
}
}
return onAir;
}
I think the solution is really simple, I just haven't come across it online.
Suppose I am given int year, int month, int day, int hour, int min, int sec.. how do I generate NSDate out of it?
I know we can use [NSDate initWithString:] but I think it gets complicated if month/day/hour/min/sec are one digit numbers.
Suppose I am given int year, int month, int day, int hour, int min, int sec.. how do I generate NSDate out of it?
Put the ints into an NSDateComponents object, then ask an NSCalendar object to change that into a date.
This here pretty much sums up how to do it.
//create a string that looks like this, "October 22, 2009" or whatever the values are
NSString* d = [NSString stringWithFormat:#"%# %#, %#", month, day, year];
NSDate* date = [NSDate dateWithNaturalLanguageString:d];
that link also shows other options for creating the date if you don't like this particular method.
just realized that you said you were given ints... you could do that with this string format:
[NSString stringWithFormat:#"%i/%i/%i", month, day, year];
I am wondering if there is some way that I can create a timer that countdown from a given time. For example, say I want this timer to last an hour. There will be a NSTextField that will show the time remaining (ex. 25 minutes), and will auto update every minute to the new value. And then, when an hour is finally passed, it will run some function. I have seen people suggesting NSTimer and NSDate for this, but am wondering what you all could suggest.
Thanks!
EDIT: My current code (timeInstance is an instance variable):
- (void)awakeFromNib:
{
timeInstance = [[NSDate date] addTimeInterval:(10 * 60)];
[timeInstance retain];
[timer invalidate];
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(timer:) userInfo:NULL repeats:YES];
}
- (void)timer:(NSTimer *)myTimer
{
NSDate *now = [NSDate date];
// Compare
}
NSTimer and NSDate sounds perfectly reasonable.
EDIT: As a side note, it might be a good idea to increase the frequency as the target time approaches; allowing you to change from hour display to minute display to second display.
I have got two timevalues in the format: %H%M%S (E.G.161500)
These values are text-based integers.
Is there a simple function in Cocoa that calculates the difference between these two integers using a 60 seconds and minutes scale?
So if
time 1 = 161500
time 2 = 171500
timedifference = 003000
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HHmmss"];
NSDate *date1 = [dateFormatter dateFromString:#"161500"];
NSDate *date2 = [dateFormatter dateFromString:#"171500"];
NSTimeInterval diff = [date2 timeIntervalSinceDate:date1]; // diff = 3600.0
The class for manipulating dates is NSDate. The method for getting time intervals is -timeIntervalSinceDate:. The result is a NSTimeInterval value, which is a double representing the interval in seconds.
You can create a NSDate object from a NSString with +dateWithString:, provided that your date is formatted as 2001-03-24 10:45:32 +0600.
try this code.
- (NSTimeInterval)intervalBetweenDate:(NSDate *)dt1 andDate:(NSDate *)dt2 {
NSTimeInterval interval = [dt2 timeIntervalSinceDate:dt1];
NSLog(#"%f",interval);
return interval;
}
I would create an NSFormatter subclass to parse time values in that format from input data (you can put one on a text field to automatically convert user input, or use it to parse from a data source in code). Have it return the combined number of seconds as an NSTimeInterval (double representing seconds) wrapped in an NSNumber. From there it's easy to subtract the difference, and display it using the same NSFormatter class you created. In both parsing and displaying values, you're the one responsible to write code converting from seconds to hours:minutes:seconds or whatever format you like. You could also convert these values to an NSDate like mouviciel mentioned, if it makes sense for your application. Just keep in mind you're always going to be storing the time difference from a reference date, usually Jan 1st 1970 (NSDate has methods to do this for you).