Convert NSString to Double for NSTimeInterval - ios

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.

Related

Need to check a code if it is not checked in last 24 hours

i need to check a block of code only once per day, i tried the below code but it is not working as per my requirement. like today date is 25-5-2017 and last checked date is 23-5-2017 also it is not coming inside the condition. i don't know where i am doing wrong.
NSDate *todayDate = [NSDate date];
NSLog(#"today date is %#",todayDate);
NSDate *lastCheckedDate = [[NSUserDefaults standardUserDefaults] objectForKey:#"LastCheckedDate"];
NSLog(#"lastCheckedDate is %#",lastCheckedDate);
if ([todayDate compare:lastCheckedDate] > 864000.0f) {
NSArray *appMsgsArray = [response valueForKey:#"AppMsgs"];
NSDictionary *mainDict = [appMsgsArray objectAtIndex:0];
NSString *appDataExpiry = [mainDict valueForKey:#"appdata_expiry"];
[stm deleteOldArticles:[appDataExpiry integerValue]];
NSDate *lastDate = [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:lastDate forKey:#"LastCheckedDate"];
}
for one day i am using 864000.0f value. can anyone help me for this, thank you.
try this:
NSDate *firstDate = [NSDate date];
NSDate *secondDate = [NSDate date];
if ([secondDate timeIntervalSinceDate:firstDate] >= 86400) {
NSLog(#"24 hours have passed...");
}

timeIntervalSinceDate not returning correct answer objective c

I'm trying to get timeIntervalSinceDate to send a log in secs of how much time has elapsed since a previous date but it isn't working. I set it for 1 minute in the future each time I test it but I not get logs that correspond like the latest log was this: 2015-09-22 16:30:04.469 Wakey Wakey[49785:7077539] Seconds nan 2015-09-22 16:30:04.470. This is the code:
NSString *dateTimeString = [dateFormatter stringFromDate: dateTimePicker.date ];
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd:MM:YYYY:ss:mm:hh"];
NSDate *dateTimeSeconds = [[NSDate alloc] init];
dateTimeSeconds = [dateFormatter1 dateFromString:dateTimeString];
NSTimeInterval secs = [currentTime timeIntervalSinceDate:dateTimeSeconds];
NSLog(#"Seconds %g", secs);
What should I do to fix it?
Why bother with NSDateFormatter. Try
NSTimeInterval seconds = [[NSDate date] timeIntervalSinceDate:dateTimePicker.date];
NSLog(#"seconds %.f", seconds);
Also use %.f instead of %g on the NSLog
Try with this
NSDate* date1 = someDate;
NSDate* date2 = someOtherDate;
NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
Please try with below date format
kTimeStampFormat #"dd-MM-yyyy'T'HH:mm:ss.SSS'Z'"
Use UTC format for consistency

How to turn NSString hexInterval into NSTimeInterval for date conversion

Currently, I am working with an existing array of NSDates in the following format:
NSDate *today = [NSDate date]; //today is used as an example
NSTimeInterval interval = [today timeIntervalSince1970];
NSString *hexInterval = [NSString stringWithFormat:#"%08x", (int)interval];
NSLog(#"hexInterval %#", hexInterval);
The dates are outputted in a format such as 4ec2acf0.
My goal is to turn these back into NSDates, as since they came from NSTimeInterval, I was wondering how I could turn it back into NSTimeIntervals given that all I have are these 8-character NSStrings.
My goal is:
//Turn NSString into NSTimeInterval here, then:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
Thanks!
You can parse hex with NSScanner, like this:
unsigned res = 0;
NSScanner *scanner = [NSScanner scannerWithString:hexInterval];
[scanner scanHexInt:&res];
NSTimeInterval interval = (NSTimeInterval)res;
// Once you have an interval, use your code:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
Note that this approach truncates the time portion of NSTimeInterval. This happens at the point when you convert NSTimeInterval to int on this line:
NSString *hexInterval = [NSString stringWithFormat:#"%08x", (int)interval];

How to get iOS date format of current date into an integer?

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));

IOS Calculate the Time Difference from Now

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);

Resources