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];
Related
I am trying to parse a clock string composed by a multiple number of minutes and convert it to a NSDate using a NSDateFormatter.
An example of the string I am trying to parse is #"1234:56", where 1234 are the minutes of the clock and 56 the seconds. I tried to use a format such as #"mmmm:ss" but it returned nil.
In case it is possible, can anyone help me with this?
Thanks
I'm not sure about the thing that you want to do, but I suggest do something like that:
NSArray *timeArray = [#"1234:56" componentsSeparatedByString:#":"];
NSUInteger minutes = [[timeArray firstObject] integerValue];
NSUInteger seconds = [[timeArray lastObject] integerValue];
NSTimeInterval totalSeconds = minutes*60+seconds;
And then you should create a new date object and work with this.
NSDate *newDate = [NSDate dateWithTimeIntervalSince1970:totalSeconds];
NSDateFormatter only works with legal date format and there is no 'mmmm'.You should get date by yourself:
NSString *str = #"234:56";
NSArray<NSString *> *components = [str componentsSeparatedByString:#":"];
NSInteger minute = 0;
NSInteger second = 0;
switch (components.count) {
case 1:
second = components[0].integerValue;
break;
case 2:
second = components[0].integerValue;
minute = components[1].integerValue;
break;
default:
break;
}
// then convert to hours.
Try this.
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
self.timerLabel.text = timeString;
If you want to convert that to HH:mm:ss then my approach will be something like:
// assuming you wouldn't have any hours in the string and format will always be minutes:seconds
NSArray *timeArray = [#"1234:56" componentsSeparatedByString:#":"];
//array's firstObject will be the "minutes/Hours"
NSString *minutesAndHours = [timeArray firstObject];
int hours = [minutesAndHours intValue]/60;
int minutes = [minutesAndHours intValue]%60;
int seconds = [timeArray lastObject];
//create the format
NSString *time = [NSString stringWithFormat:#"%d:%d:%d",hours,minutes,seconds];
//then use the time format
NSString *time = [NSString stringWithFormat:#"%d:%d:%d",hours,minutes,seconds];
NSDateFormatter *format = [NSDateFormatter new];
[format setDateFormat:#"HH:mm:ss"];
NSDate *date = [format dateFromString:time];
something like this
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);
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.
I have problems printing a date as NSString. I have stored current date and time at certain points of my app lifecycle this way:
NSDate *current = [NSDate date];
long currentTime = [current timeIntervalSince1970];
Now, I need to show those dates in UILabels. I tried this way:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:currentTime];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy - HH:mm:ss"];
NSString *stringFromDate = [formatter stringFromDate:date];
but I'm not getting the correct date nor the time. What could I be missing?
Thanks!
Try this,
NSString *stringFromDate=[NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
also you can change the datestyle and timestyle.
Your currentTime variable is a long, and not an NSTimeInterval (a double). You are losing not only the fractional part (less important), but the upper range of the time interval. Change it to:
NSTimeInterval currentTime = [current timeIntervalSince1970];
How to convert an NSDate into Unix timestamp? I've read many posts which do the reverse. But I'm not finding anything related to my question.
I believe this is the NSDate's selector you're looking for:
- (NSTimeInterval)timeIntervalSince1970
A Unix timestamp is the number of seconds since 00:00:00 UTC January 1, 1970. It's represented by the type time_t, which is usually a signed 32-bit integer type (long or int).
iOS provides -(NSTimeInterval)timeIntervalSince1970 for NSDate objects which returns the number of seconds since 00:00:00 GMT January 1, 1970. NSTimeInterval is a double floating point type so you get the seconds and fractions of a second.
Since they both have the same reference (midnight 1Jan1970 UTC) and are both in seconds the conversion is easy, convert the NSTimeInterval to a time_t, rounding or truncating depending on your needs:
time_t unixTime = (time_t) [[NSDate date] timeIntervalSince1970];
You can create a unix timestamp date from a date this way:
NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];
- (void)GetCurrentTimeStamp
{
NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
[objDateformat setDateFormat:#"yyyy-MM-dd"];
NSString *strTime = [objDateformat stringFromDate:[NSDate date]];
NSString *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter.
NSDate *objUTCDate = [objDateformat dateFromString:strUTCTime];
long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);
NSString *strTimeStamp = [Nsstring stringwithformat:#"%lld",milliseconds];
NSLog(#"The Timestamp is = %#",strTimestamp);
}
- (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *objDate = [dateFormatter dateFromString:IN_strLocalTime];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
NSString *strDateTime = [dateFormatter stringFromDate:objDate];
return strDateTime;
}
NOTE :- The Timestamp must be in UTC Zone, So I convert our local Time to UTC Time.
Swift
Updated for Swift 3
// current date and time
let someDate = Date()
// time interval since 1970
let myTimeStamp = someDate.timeIntervalSince1970
Notes
timeIntervalSince1970 returns TimeInterval, which is a typealias for Double.
If you wanted to go the other way you could do the following:
let myDate = Date(timeIntervalSince1970: myTimeStamp)
If you want to store these time in a database or send it over the server...best is to use Unix timestamps. Here's a little snippet to get that:
+ (NSTimeInterval)getUTCFormateDate{
NSDateComponents *comps = [[NSCalendar currentCalendar]
components:NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit
fromDate:[NSDate date]];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:[[NSTimeZone systemTimeZone] secondsFromGMT]];
return [[[NSCalendar currentCalendar] dateFromComponents:comps] timeIntervalSince1970];
}
My preferred way is simply:
NSDate.date.timeIntervalSince1970;
As per #kexik's suggestion using the UNIX time function as below :
time_t result = time(NULL);
NSLog([NSString stringWithFormat:#"The current Unix epoch time is %d",(int)result]);
.As per my experience - don't use timeIntervalSince1970 , it gives epoch timestamp - number of seconds you are behind GMT.
There used to be a bug with [[NSDate date]timeIntervalSince1970] , it used to add/subtract time based on the timezone of the phone but it seems to be resolved now.
[NSString stringWithFormat: #"first unixtime is %ld",message,(long)[[NSDate date] timeIntervalSince1970]];
[NSString stringWithFormat: #"second unixtime is %ld",message,[[NSDate date] timeIntervalSince1970]];
[NSString stringWithFormat: #"third unixtime is %.0f",message,[[NSDate date] timeIntervalSince1970]];
first unixtime 1532278070
second unixtime 1532278070.461380
third unixtime 1532278070
If you need time stamp as a string.
time_t result = time(NULL);
NSString *timeStampString = [#(result) stringValue];