I initiated an NSDate with [NSDate date]; and I want to check whether or not it's been 5 hours since that NSDate variable. How would I go about doing that? What I have in my code is
requestTime = [[NSDate alloc] init];
requestTime = [NSDate date];
In a later method I want to check whether or not it's been 12 hours since requestTime. Please help! Thanks in advance.
NSInteger hours = [[[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:requestTime toDate:[NSDate date] options:0] hour];
if(hours >= 5)
// hooray!
int seconds = -(int)[requestTime timeIntervalSinceNow];
int hours = seconds/3600;
Basically here I'm asking how many seconds have passed since we first got our requestTime. Then with a little math magic, aka dividing by the number of seconds in an hour, we can get the number of hours that have passed.
A word of caution. Make sure you use the "retain" keyword when setting the requesttime. xcode likes to forget what NSDate objects are set to without it.
requestTime = [[NSDate date] retain];
Try using this method, or something along these lines.
- (int)hoursSinceDate :(NSDate *)date
{
#define NUBMER_OF_SECONDS_IN_ONE_HOUR 3600
NSDate *currentTime = [NSDate date];
double secondsSinceDate = [currentTime timeIntervalSinceDate:date];
return (int)secondsSinceDate / NUBMER_OF_SECONDS_IN_ONE_HOUR;
}
You can then do a simple check on the integer hour response.
int hours = [dateUtilityClass hoursSinceDate:dateInQuestion];
if(hours < 5){
# It has not yet been 5 hours.
}
Related
I am trying to find how many milliseconds into the current day we are. I can't find a method to return the time in milliseconds ignoring date, so I figured I could calculate it off of the value returned by timeIntervalSince 1970 method.
I did this:
NSLog(#"%f", [[NSDate date] timeIntervalSince1970]);
2013-05-21 16:29:09.453 TestApp[13951:c07] 1369171749.453490
Now my assumption is that, since there are 86,400 seconds in a day I could divide this value by 86400 and get how many days have elapsed since 1970. Doing this gives me 15846.8952483 days. Now, if my assumption holds, I am 89.52483% through the current day. So multiple 24 hours by 86.52659% would give me a current time of the 21.4859592 hour or about 09:29 PM. As you can see from my NSLog this is about 5 hours from the real time, but I believe the interval returned is GMT so this would be 5 hours ahead of my time zone.
So I figured, well what the heck, I'll just roll with it and see what happens.
I cut off the decimal places by doing:
float timeSince1970 = [[NSDate date] timeIntervalSince1970]/86400.0;
timeSince1970 = timeSince1970 - (int)timeSince1970
Then calculate the milliseconds that have taken place thus far today:
int timeNow = timeSince1970 * 86400000;
NSLog(#"%i", timeNow);
2013-05-21 16:33:37.793 TestApp[14009:c07] 77625000
Then I convert the milliseconds (which still seem appropriate) to NSDate:
NSString *timeString = [NSString stringWithFormat:#"%d", timeNow];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"A"]
NSDate *dateNow = [dateFormatter dateFromString:timeString];
NSLog(#"%#", dateNow);
2013-05-21 16:29:09.455 TestApp[13951:c07] 2000-01-02 03:29:00 +0000
And there is my problem. Rather than returning a 2000-01-01 date with some hours and minutes attached, it is returning a 2000-01-02 date. Why!?
EDIT
I got it working by "removing" the extra 5 hours I noted in the above with:
int timeNow = (timeSince1970 * 86400000) - (5 * 60 * 60 * 1000);
I don't understand why this is necessary though. If someone can explain I'd greatly appreciate it.
EDIT 2
Perhaps I should be asking a more elementary question about how to accomplish the task I'm trying to accomplish. I care about times (for example, 4pm is important but I could care less about the date). I've been storing these in NSDates created by:
[dateFormatter setDateFormat:#"hh:mm a"];
[dateFormatter dateFromString#"04:00 PM"];
All this seems to be going fine. Now I want to compare current time to my saved time and find out if it is NSOrderedAscending or NSOrderedDescending and respond accordingly. Is there a better way to be accomplishing this?
You need to use NSCalendar to generate NSDateComponents based on right now, then set the starting hour, minute, and second all to 0. That will give you the beginning of today. Then you can use NSDate's -timeIntervalSinceNow method to get back the time elapsed between now and your start date.
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
// BUILD UP NSDate OBJECT FOR THE BEGINNING OF TODAY
NSDateComponents *comps = [cal components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate: now];
comps.hour = 0;
comps.minute = 0;
comps.second = 0;
// USE CALENDAR TO GENERATE NEW DATE FROM COMPONENTS
NSDate *startOfToday = [cal dateFromComponents: comps];
// YOUR ELAPSED TIME
NSLog(#"%f", [startOfToday timeIntervalSinceNow]);
Edit 1
If you're just looking to compare some NSDateObjects you can see if the time interval between then and now is negative. If so, that date is in the past.
NSDate *saveDate = [modelObject lastSaveDate];
NSTimeInterval difference = [saveDate timeIntervalSinceNow];
BOOL firstDateIsInPast = difference < 0;
if (firstDateIsInPast) {
NSLog(#"Save date is in the past");
}
You could also use compare:.
NSDate* then = [NSDate distantPast];
NSDate* now = [NSDate date];
[then compare: now]; // NSOrderedAscending
The part of your question that says that you want to calculate "how many milliseconds into the current day we are" and then "4pm is important but I could care less about the date" makes it not answerable.
This is because "today" there could have been a time change, which changes the number of milliseconds since midnight (by adding or subtracting an hour, for instance, or a leap second at the end of a year, etc....) and if you don't have the date, you can't determine the number of milliseconds accurately.
Now, to address your edited question: If we assume today's date, then you need to use the time that you have stored and combine it with today's date to get a "specific point in time" which you can compare to the current date and time:
NSString *storedTime = #"04:00 PM";
// Use your current calendar
NSCalendar *cal = [NSCalendar currentCalendar];
// Create a date from the stored time
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"hh:mm a"];
NSDate *storedDate = [dateFormatter dateFromString:storedTime];
// Break it up into its components (ie hours and minutes)
NSDateComponents *storedDateComps = [cal components:NSHourCalendarUnit | NSMinuteCalendarUnit
fromDate:storedDate];
// Now we get the current date/time:
NSDate *currentDateAndTime = [NSDate date];
// Break it up into its components (the date portions)
NSDateComponents *todayComps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:currentDateAndTime];
// Combine with your stored time
todayComps.hour = storedDateComps.hour;
todayComps.minute = storedDateComps.minute;
// Create a date from the comps.
// This will give us today's date, with the time that was stored
NSDate *currentDateWithStoredTime = [cal dateFromComponents:todayComps];
// Now, we have the current date and the stored value as a date, so it is simply a matter of comparing them:
NSComparisonResult result = [currentDateAndTime compare:currentDateWithStoredTime];
it is returning a 2000-01-02 date. Why!?
Because your dateFormatter uses the current system locale's timezone.
If you insert ...
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
... your date formatter will interpret the string correctly. But why not creating the date directly:
NSDate *dateNow = [NSDate dateWithTimeIntervalSinceReferenceDate:timeNow];
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
hours minutes seconds to seconds ios
I have a time formatted as such
// format: HH:mm:ss,AAA
// example for 2 hours, 35 minutes, 15 seconds, and 207 milliseconds
02:35:15,207
I'm trying to convert that into seconds as a double. The above example would turn into:
// 2 hrs * 3600 + 25 min * 60 + 15.207
9315.207
I figure I can pick apart each element with a scanner, but I'm thinking there's probably an easier way. I tried using NSDateFormatter but I need this as a double, not as an NSDate. Any suggestions? Thanks.
Further FYI
This is for use with the MPMoviePlayer and the currentTime property is a double. For any given section where I have data to show, I am checking if dataStartTime <= playerTime < dataEndTime. So I'm using double because that's the type for currentTime already.
Here is the solution, the idea is simple get two date one with your time and one with 00:00:00,000 time then take difference of their time.
- (double)secondsFromString:(NSString*)str {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss,SSS"];
NSString *dateString = #"1970-01-01";
NSDate *date = [formatter dateFromString:[NSString stringWithFormat:#"%# %#",dateString,str]];
NSDate *refDate = [formatter dateFromString:[NSString stringWithFormat:#"%# 00:00:00,000",dateString]];
double time = [date timeIntervalSince1970] - [refDate timeIntervalSince1970];
return time;
}
This is the situation here. I have current time in epoch. also I have number of days. I want to find the difference between the 2 to give some past time in epoch format. i.e.
currentEpochTime - (x days) to give some past time in epoch format.
This is what I have gotten so far -
+ (double)currTimeInEpoch
{
NSDate *todayDate = [NSDate date];
double ti = [todayDate timeIntervalSince1970]*1000;
return ti;
}
+ (NSString *)timeDiff:(double)epoch diff:(double)diffInDays
{
double past = epoch - (diffInDays * 24 * 60 * 60 * 1000);
return [[NSNumber numberWithDouble:past] stringValue];
}
Is what I am doing correct? Not sure about it. Is there any simpler way to do this ?
It's dangerous to go alone. Take this.
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = -40; // Number of days to subtract
NSDate *newDate = [[NSCalendar autoupdatingCurrentCalendar] dateByAddingComponents:dateComponents toDate:[NSDate date] options:0];
NSTimeInterval newDateInEpochTime = [newDate timeIntervalSince1970] * 1000;
In My application I have to complete a particular task in given time.So first i calculated the time complete the task in seconds and then add that time to the current that like this.
NSDate *mydate = [NSDate date];
NSTimeInterval TotalDuraionInSec = sec.cal_time * 60;
TaskCmpltTime = [mydate addTimeInterval:TotalDuraionInSec];
NSLog(#"task will be completed at%#",TaskCmpltTime);
now I compare time like this
if([CurrentTime isEqualToDate:AfterCmpltTime]){
NSLog (#"Time Finish");
}
but I want to know is Time is left or not.Is current time is less then or greater then current time how can i know this ?
timeIntervalSinceNow compares the NSDate with Now. if NSDate is after Now the return value is possitive, if the date is earlier than Now the result is negative.
double timeLeft = [TaskCompltTime timeIntervalSinceNow];
if( timeLeft > 0.0 )
// still time left
else
//time is up
I have an example where I get the time from a picker and check if its today or tomorrow. You should be able to just take the code and use it in your way...
int selectedHour = [customPickerView selectedRowInComponent:0];
int selectedMinute = [customPickerView selectedRowInComponent:1];
NSDate *today = [NSDate date];
NSDateFormatter *weekdayFormatter = [[[NSDateFormatter alloc] init]autorelease];
NSDateFormatter *hmformatter = [[[NSDateFormatter alloc] init]autorelease];
[hmformatter setDateFormat: #"hh mm"];
[weekdayFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[weekdayFormatter setDateFormat: #"EE"];
// NSString *formattedDate = [formatter stringFromDate: today];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease];
NSDateComponents *dateComponentsToday = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit) fromDate:today];
NSInteger currentHour = [dateComponentsToday hour];
NSInteger currentMinute = [dateComponentsToday minute];
NSString *weekday;
if ((selectedHour > currentHour) | ((selectedHour == currentHour) & (selectedMinute > currentMinute))) {
//so we are still in today
weekday = [weekdayFormatter stringFromDate: today];
weekday = NSLocalizedString(#"today", #"today");
} else {
//the timer should start tomorrow
NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate *tomorrow = [today dateByAddingTimeInterval:secondsPerDay];
weekday = [weekdayFormatter stringFromDate: tomorrow];
weekday = NSLocalizedString(#"tomorrow", #"tomorrow");
}
Yeah, for your purposes it's probably best to work in time intervals. The NSTimeInterval in Objective-C is an alias for double, and it represents a time value in seconds (and, of course, fractions, down to at least millisecond resolution).
There are several methods on NSDate for this -- +timeIntervalSinceReferenceDate, which returns the number of seconds since Jan 1, 2001, -timeIntervalSinceReferenceDate, which returns the difference in time between the supplied NSDate object and Jan 1, 2001, -timeIntervalSinceDate:, which returns the difference in seconds between the two NSDate objects, and -timeIntervalSinceNow, which returns the difference between the current time and the NSDate object.
Lots of times it's most convenient to store an NSDate value as an NSTimeInterval instead (eg, timeIntervalSinceReferenceDate). This way it doesn't have to be retained and disposed, etc.
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];