I get a Unix timestamp (Created at time) from server of which I get the NSDate object using :
NSTimeInterval interval = [str doubleValue];
NSDate *timeStamp = [NSDate dateWithTimeIntervalSince1970:interval];
I need to find the time difference between the above created time and current time and display in hh:mm:ss format. I coded it :-
NSTimeInterval timeDiff = [agent.chatStartTimeStamp timeIntervalSinceNow];
// NSDate *now = [NSDate date];
// timeDiff = [now timeIntervalSinceDate:agent.chatStartTimeStamp]; // RETURNS NEGATIVE
// Divide the interval by 3600 and keep the quotient and remainder
div_t h = div(timeDiff, 3600);
int hours = h.quot;
// Divide the remainder by 60; the quotient is minutes, the remainder
// is seconds.
div_t m = div(h.rem, 60);
int minutes = m.quot;
int seconds = m.rem;
NSString *str = [NSString stringWithFormat:#"%d:%d%d", hours, minutes, seconds];
cell.timeLabel.text = str;
NSLog(#"*********** CV CTRL - AGENT CHATSTARTTIME - %# TIME DIFFERNCE = %f STR = %#", agent.chatStartTimeStamp, timeDiff, str);
The logs for the above 2 codes -
AGENT CHATSTART TIME - 1403342129.980000 SET TIME - 2014-06-21 09:15:29 +0000
*********** CV CTRL - AGENT CHATSTARTTIME - 2014-06-21 09:15:29 +0000 TIME DIFFERNCE = 130.419857 STR = 0:210
The above code gives me results as - suppose the value is 0:2:10, then this value reduces to 0:1:40, 0:1:6, 0:-1....
What I am looking out is - the time difference should increase as the created at time will be something before/earlier current time only. So I want that value of startTime should be deducted from now i.e. now - startTime (time). And I believe this will give me results as I am expecting. I tried with [now timeIntervalSinceDate:agent.chatStartTimeStamp]; but that returns negative response.
UPDATE
This is how I convert the unix timestamp to loca time :-
+ (NSDate *)getNSDateFromUnixTimeStamp : (NSString *) unixTime {
NSString *str = [NSString stringWithFormat:#"%f",[unixTime doubleValue]/(double)1000];
NSTimeInterval interval = [str doubleValue];
NSDate *timeStamp = [NSDate dateWithTimeIntervalSince1970:interval];
str = nil;
unixTime = nil;
return timeStamp;
}
And log for the same :-
2014-06-23 12:24:38.046 MintChat[1021:70b] AGENT CHATSTART TIME - 1403506610.771000 SET TIME - 2014-06-23 06:56:50 +0000
My system time is 12:24:38 & the unixtimestamp is also the current time at just few secs before, so I guess shouldn't the unix time set should also have time as almost same.
Can anyone help me how to get this simple time difference. Where am I going wrong ? I searched a lot on the subject, but couldn't get the expected results.
Any help is highly appreciated.
Thanks
Your commented code, [now timeIntervalSinceDate:agent.chatStartTimeStamp]; is correct. From the NSDate documentation -
Return Value
The interval between the receiver and the current date and time. If the receiver is earlier than the current date and
time, the return value is negative.
So, you can simply take the absolute value to get the number of seconds -
NSTimeInterval timeDiff = fabs([now timeIntervalSinceDate:agent.chatStartTimeStamp]);
Once you have the time interval you can use this answer to format it -
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeDiff];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
NSString *formattedDate = [dateFormatter stringFromDate:date];
NSLog(#"hh:mm:ss %#", formattedDate);
Related
Through my App users can order specific food item in restaurants..The thing is that if a user want to order a specific product he can give atleast 6 hrs time for the restaurant to deliver the product.For example you are the user,right now time is 12:00pm..In the app,user can select the timings of DELIVERY through UIDatepicker.Here if user selects the time before 06:00pm,one alert view will generate with message "please give 6hrs time for your order".Here i have to compare system time and UIDatepickers time.I found one method,,but it is not useful.
if ([self.datePicker.date compare:currentdate] == NSOrderedDescending){
NSLog(#"Descending");
}
Please help me...Thanks in advance
Either you can compare the selected time by
NSDate *date1 = [NSDate date];
NSDate *date2 = datePicker.date;
NSTimeInterval elapsed = [date1 timeIntervalSinceDate:date2];
Also you can set minimum time of date picker after 6 hours
NSDate *mydate = [NSDate date];
NSTimeInterval secondsInSixHours = 6 * 60 * 60;
NSDate *dateSixHoursAhead = [mydate dateByAddingTimeInterval:secondsInSixHours];
[datePicker setMinimumDate:dateSixHoursAhead];
use this
if ([[NSDate date] isEqualToDate: currentdate) {
NSLog(#"currentDate is equal to currentdate");
}
You are actually looking for time difference , here is the code :
NSLog(#"please give %#fhrs time for your order",[self.datePicker.date timeIntervalSinceDate:[NSDate date]]);
Use this method. The best way of doing comparison between two dates:
- (void)pickerDateIsSmallerThanCurrent:(NSDate *)checkDate
{
NSDate* enddate = checkDate;
NSDate* currentdate = [NSDate date];
NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
double secondsInMinute = 60;
NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;
if (secondsBetweenDates == 0)
//both dates are equal
else if (secondsBetweenDates < 0)
//selected date is smaller than current date
else
//selected date is greater than current date
}
This question already has answers here:
how to split strings in objective c
(4 answers)
Closed 8 years ago.
NOTE: I have used the share knowledge feature to answer this question as a whole and not simply one question which is commonly asked - "Splitting strings"
2 questions I have come across but never together are:
How do I split Strings? (I acknowledge this question alone has been answered a few times)
How do I calculate the difference between 2 times as strings and display in time format (00:00:00)?
The purpose of this question is to help people who are storing times are strings in core data to be able to calculate the difference between the two. I used the "share knowledge" feature to answer this question and have not simply answered. Please see below.
Since you're coming from strings, you'll need to change them to NSDate objects. You'll use a formatter to do so.
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"HH:mm:ss"];
// I don't know what date format you're coming from, you should of course use yours. check out the doc for more info.
NSDate *date1 = [dateFormat dateFromString:string1];
NSDate *date2 = [dateFormat dateFromString:string2];
Now you have date objects that are coming from your strings.
If you want to know the time between time dates (in seconds or other)
(from this post)
NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
NSTimeInterval gives you the difference in seconds, you can just calculate from there if you want hours, days, etc.
But sometimes, you might only need to know if a date is before or after another. Then you should use date compare, which returns a NSOrderingDesc or Asc or Same , like this:
//Then the comparison will tell which is earlier/later/same:
if ([date1 compare:date2] == NSOrderedDescending) {
NSLog(#"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
NSLog(#"date1 is earlier than date2");
} else {
NSLog(#"dates are the same");
}
First we establish the format of the date like so. I am using HH:MM:SS format. Format yours to suit your saved string.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:#"HH:mm:ss"];
The second part is referencing your strings. I create a new reference just to keep it tidy when converting String Date to NSDate. In my example I have declared a reference to Core Data in my .h file so I reference as follows.
NSString * StringTime1 = self.coreDataReference.time1;
NSString * StringTime2 = self.coreDataReference.time2;
Convert the strings to date:
NSDate *time1 = [dateFormat dateFromString:StringTime1];
NSDate *time2 = [dateFormat dateFromString:StringTime2];
I next get the difference by getting the time interval between the times. I am comparing the latest saved time (time2) against the first save time (time1). This method essentially subtracts whatever time is allocated second from the first, which in this case tim2 subtracts time1. You will see why in a moment.
NSTimeInterval distanceBetweenDates = [time2 timeIntervalSinceDate:time1];
For displaying purposes, I convert the time which is now a double (NSTimeInterval is a double, check https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html for more information) and then convert them into hours, minutes and second values.
int timeInt = (int) distanceBetweenDates;
//I convert the values into the time value
int hours = timeInt / 3600;
int minutes = (timeInt / 60) % 60;
int seconds = timeInt % 60;
FInally we display the results in log and if you have a label display there as well.
NSLog(#"The total time is: %02u:%02u:%02u", hours, minutes, seconds);
NSString * time = [NSString stringWithFormat:#"%02u:%02u:%02u", hours, minutes, seconds];
self.totalLoginTimeLabel.text = time;
I hope this helps anyone investigating.
The whole code here:
-(void) calculateTimeIntervalFromStrings{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:#"HH:mm:ss"];
NSString * StringTime1 = self.coreDataReference.time1;
NSString * StringTime2 = self.coreDataReference.time2;
NSDate *time1 = [dateFormat dateFromString:StringTime1];
NSDate *time2 = [dateFormat dateFromString:StringTime2];
NSTimeInterval distanceBetweenDates = [time2 timeIntervalSinceDate:time1];
int timeInt = (int) distanceBetweenDates;
//I convert the values into the time value
int hours = timeInt / 3600;
int minutes = (timeInt / 60) % 60;
int seconds = timeInt % 60;
NSLog(#"The total time is: %02u:%02u:%02u", hours, minutes, seconds);
NSString * time = [NSString stringWithFormat:#"%02u:%02u:%02u", hours, minutes, seconds];
self.timeDifferenceLabel.text = time;
}
To call this method, place in your viewDidLoad method like so:
[self calculateTimeIntervalFromStrings];
I am trying to figure out how to get the current date and time into a number up to the seconds?
I saw this post What format string do I use for milliseconds in date strings on iPhone? but I am actually trying to get it into just a number...
EDIT: Sorry meant seconds
if you want UTC timestamp and want to store in int than on 32 bit this is not possible use instead long long which has larger range and can be used as integer
NSString *dateValue = #"2011-06-23T13:13:00.000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSString *formatString = #"yyyy-MM-dd'T'HH:mm:ss.SSS";
[formatter setDateFormat:formatString];
NSDate *date = [formatter dateFromString:dateValue];
long long dateInMillis = [date timeIntervalSince1970]*1000; //This will give milliseconds
long dateInSeconds = [date timeIntervalSince1970]; //This will give seconds
EDIT: For current date in long value use
//This will give seconds of current date
long dateInSeconds = [[NSDate date] timeIntervalSince1970];
You can convert an NSDate to a double using:
NSTimeInterval seconds = [[NSDate date] timeIntervalSince1970];
millis:
long long milliseconds = llround(([[NSDate date] timeIntervalSince1970] * 1000.0));
Time profiler say that my code to expressive in memory and I see lags while scrolling tableView.
How can I replace this code?
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm:ss"];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_duration doubleValue]];
return [dateFormatter stringFromDate:date];
_duration have value 123
I need string from _duration like 2:03 sec
Two options:
1) Create the date formatter once and reuse it.
2) Don't use a date formatter. There's no need. It's trivial to convert your duration to minutes and seconds.
int duration = [_duration intValue];
int mins = duration / 60;
int secs = duration % 60;
return [NSString stringWithFormat:#"%02d:%02d", mins, secs];
The end result that I need is that I want to find out out how long ago a comment was posted. To do this I started off by doing something like:
double timestampComment = [[testArray objectForKey:#"timestamp"] doubleValue]/1000;
NSDate *date = [NSDate date];
NSLog(#"Date: %#", date);
NSTimeInterval timestamp = (NSTimeInterval)timestampComment;
NSDate *actualTime = [NSDate dateWithTimeInterval:timestamp sinceDate:date];
But that didn't work and returned something like 5213 months ago (it was only posted last week!) I then done some searching around and found out that the double value of the timestamp, i.e. 1377775454768 was actually 1377775454768.000000, so that explains why the timing was so wrong.
I've now tried done some console logging and still cant get the double value with no decimal values for the NSTimeInterval. This is what I have tried now:
double timer = [[testArray objectForKey:#"timestamp"]doubleValue];
//NSString *timerStr = [NSString stringWithFormat:#"%.0f", timer];
NSString *timerCount = [testArray objectForKey:#"timestamp"];
NSTimeInterval timeIntervalComment = timer;
//NSTimeInterval timeIntervalCount = timerCount;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeIntervalComment];
NSLog(#"Timer: %#", timerCount);
NSString *rightTimestr = [NSString stringWithFormat:#"%.0f", timeIntervalComment];
int timerTest = [rightTimestr intValue];
NSTimeInterval timeTest = (NSTimeInterval)[timerCount doubleValue];
NSDate *testDate = [NSDate dateWithTimeIntervalSince1970:timeTest];
NSLog(#"rightTimestr %#", rightTimestr);
NSLog(#"timerTest %d", timerTest);
NSLog(#"%f", [timerCount doubleValue]);
NSLog(#"Test Date: %#", testDate);
NSLog(#"Timer 2: %f", timer);
NSLog(#"date: %#", date);
And this is the result of the logging:
Timer: 1377775454768
rightTimestr 1377775454768
timerTest 2147483647
1377775454768.000000
Test Date: 45629-12-19 04:06:08 +0000
Timer 2: 1377775454768.000000
date: 45629-12-19 04:06:08 +0000
Any help would be appreciated. Thanks
You want the difference in time between now and when the comment was posted. Untested:
double timestampComment = [[testArray objectForKey:#"timestamp"] doubleValue]/1000;
NSTimeInterval diff = (NSTimeInterval)timestampComment - [[NSDate date] timeIntervalSince1970];
// diff now contains the number of seconds since the comment was posted
However you don't want to use NSDate to format this difference, as NSDate is for manipulating dates, not time deltas. You'll need to use the kind of code used here on Stackoverflow to show when answers were posted, for example if < 1 hour then show "X minutes ago", else show the date the comment was posted, etc.