Convert epoch milliseconds to NSDate - ios

I want to convert milliseconds elapsed since Jan 1 1970 to NSDate without loosing milliseconds. Every solution says to divide milliseconds by 1000 and use dateWithTimeIntervalSince1970. but I want to keep the preserve the to milliseconds as well.

The parameter to dateWithTimeIntervalSince1970 is a NSTimeInterval, which is not an integer value (it's a double). There's no reason to lose milliseconds. Just don't use integers when you perform your division.
For example:
long long milliseconds = 1576058147753;
NSTimeInterval seconds = (NSTimeInterval)milliseconds / 1000.0;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"];
[formatter setLocalizedDateFormatFromTemplate:#"dMMMMyyyyHHmmssSSS"];
December 11, 2019, 01:55:47.753
Note the milliseconds of 753 are there.

You can get date in this way.You have to pass timeinterval and date format as per your requirement.
-(NSString *)getStringFromDate:(double)interval withFormat:(NSString*)format
{
if (interval == 0)
{
return #"";
}
double seconds = interval;
NSTimeInterval timeInterval = (NSTimeInterval)seconds;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter* df_utc = [[NSDateFormatter alloc] init];
[df_utc setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[df_utc setDateFormat:format];
NSString *Date=[df_utc stringFromDate:date];
return Date;
}
Hope this will help you.

Related

How to remove the timezone offset from an NSDate

I am trying to get just yyyy-MM-dd HH:mm from an NSDateFormatter.
But the string spits out Historical Date: 2016-08-23 14:03:00 +0000
I do not want the seconds or the +0000.
What am I doing wrong?
int seconds = -( days * (24 * 60 * 60)); //24 hours, times 60 minutes, times 60 seconds
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd HH:mm"];
NSString* stringFromDate = [format stringFromDate:[NSDate date]];
NSDate * pastDate = [[format dateFromString:stringFromDate] dateByAddingTimeInterval:seconds];
NSLog(#"Date: %#", pastDate);
It happens because you printing NSDate object.
NSDate object encapsulates a single point in time, it is not responsible for it's string representation.
What you really need to do, is to calculate exact date you need, and then format it into NSString.
Something like that:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *pastDate = [[NSDate date] dateByAddingTimeInterval:seconds];
NSString *yourDateInString = [dateFormatter stringFromDate:pastDate];
NSLog(#"%#", yourDateInString);
Also, it is good practice to use NSCalendar and NSCalendarComponents to manipulate with dates and calculate new dates instead of just adding time interval.
I tried your coding first
int seconds = -( 24 * (24 * 60 * 60)); //24 hours, times 60 minutes, times 60 seconds
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd HH:mm"];
NSString* stringFromDate = [format stringFromDate:[NSDate date]];
NSDate * pastDate = [[format dateFromString:stringFromDate] dateByAddingTimeInterval:seconds];
NSLog(#"The pastDate is - %#",pastDate);
The printed result is
The pastDate is - 2016-07-31 14:30:00 +0000
NSDate gets +0000
Then I tried with string
NSString *stringDate = [format stringFromDate:pastDate];
NSLog(#"The Date is: %#", stringDate);
Now the printed result is
The Date is: 2016-07-31 20:00
String does not have +0000

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

Convert date to timestamp in iOS

How do you convert any given date to milliseconds? For example, 2014-01-23 to timestamp conversion.
NSDate *date = [dateFormatter dateFromString:#"2014-01-23"];
NSLog(#"date=%#",date);
NSTimeInterval interval = [date timeIntervalSince1970];
NSLog(#"interval=%f",interval);
NSDate *methodStart = [NSDate dateWithTimeIntervalSince1970:interval];
[dateFormatter setDateFormat:#"yyyy/mm/dd "];
NSLog(#"result: %#", [dateFormatter stringFromDate:methodStart]);
Output result: 1970/30/01
Swift
Convert the current date/time to a timestamp:
// current date and time
let someDate = Date()
// time interval since 1970
let myTimeStamp = someDate.timeIntervalSince1970
See also
Convert Date to Integer in Swift
Creating a Date and Time in Swift
How to get the current time as datetime
Have it a try. "mm" stands for minute while "MM" stands for month.
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init] ;
[dateFormatter setDateFormat:#"yyyy-MM-dd"] ;
NSDate *date = [dateFormatter dateFromString:#"2014-01-23"] ;
NSLog(#"date=%#",date) ;
NSTimeInterval interval = [date timeIntervalSince1970] ;
NSLog(#"interval=%f",interval) ;
NSDate *methodStart = [NSDate dateWithTimeIntervalSince1970:interval] ;
[dateFormatter setDateFormat:#"yyyy/MM/dd "] ;
NSLog(#"result: %#", [dateFormatter stringFromDate:methodStart]) ;
NSTimeinterval is really a double, being seconds since a particular date (in your case, the start of 1970)
NOTE :- UNIX Timestamp format contains 13 Digits so we need a 1000 multiplication with the result.
And the timestamp must be UTC ZONE not our local Time Zone.
- (void)GetCurrentTimeStamp
{
NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
[objDateformat setDateFormat:#"yyyy-MM-dd"];
NSString *strUTCTime = [self GetUTCDateTimeFromLocalTime:#"2014-01-23"];
NSDate *objUTCDate = [objDateformat dateFromString:strUTCTime];
long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);
NSLog(#"Local Time = %#---- UTC = %# ----- TimeSatmp = %ld ---- TimeStamp = %lld",strTime,strUTCTime,unixTime,milliseconds);
}
- (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;
}
[date1 timeIntervalSinceDate:date2] will return seconds from two NSDate objects.
double seconds = [date1 timeIntervalSinceDate:date2];
double milliSecondsPartOfCurrentSecond = seconds - [seconds intValue];
milliSecondsPartOfCurrentSecond

JSON date string conversion issue in iOs

I am getting some UTC date strings from WCF Rest service and here is the format:
/Date(1354851639500+0530)/
I used the following code to convert the date:
//jsonDateString = 1354851639500+0530
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; //get number of seconds to add or subtract according to the client default time zone
NSTimeInterval unixTime = [[jsonDateString substringWithRange:NSMakeRange(0, 13)] doubleValue] / 1000; //WCF will send 13 digit-long value for the time interval since 1970 (millisecond precision) whereas iOS works with 10 digit-long values (second precision), hence the divide by 1000
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss a ZZZZ"];
NSString *stringFromDAte = [dateFormatter stringFromDate:[[NSDate dateWithTimeIntervalSince1970:unixTime] dateByAddingTimeInterval:offset]];
NSLog(#"Server GMT: %#", stringFromDAte);
NSDate *currentDadte = [dateFormatter dateFromString:stringFromDAte];
NSTimeInterval interval = [currentDadte timeIntervalSinceDate:[NSDate date]];
return [self dailyLanguage:interval];
But when I convert the time is not correct. I need to get the UTC time of the receiving time. But I am getting the time value without the offset value.
For example: if josnDate = 1354851639500+0530,
i am getting, 2012-12-07 03:40:39 AM GMT, but i should get 2012-12-07 09:10:39 (approx).
How can I do this? Please help.
Try this Code
- (NSDate *)deserializeJsonDateString: (NSString *)jsonDateString
{
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; //get number of seconds to add or subtract according to the client default time zone
NSInteger startPosition = [jsonDateString rangeOfString:#"("].location + 1; //start of the date value
NSTimeInterval unixTime = [[jsonDateString substringWithRange:NSMakeRange(startPosition, 13)] doubleValue] / 1000; //WCF will send 13 digit-long value for the time interval since 1970 (millisecond precision) whereas iOS works with 10 digit-long values (second precision), hence the divide by 1000
[[NSDate dateWithTimeIntervalSince1970:unixTime] dateByAddingTimeInterval:offset];
return date;
}
For more detail answer follow this link
http://goo.gl/lE6ut
You can try this
NSString *jsonDateString = [SingleResponseObject objectForKey:#"datetime"];;
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSTimeInterval unixTime = [[jsonDateString substringWithRange:NSMakeRange(0, 13)] doubleValue] / 1000;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss a ZZZZ"];
NSString *stringFromDAte = [dateFormatter stringFromDate:[[NSDate dateWithTimeIntervalSince1970:unixTime] dateByAddingTimeInterval:offset]];
cell.date.text = stringFromDAte;

double converted to hours minutes and seconds with NSdateformatter returning wrong answer

i am using the following code to convert a value of 18900 into hh:mm:ss
unfortunately the value returned doesn't seem right as it gives me 06:15:00
can anyone please advise why its going wrong
thanks
-(NSString*)setHours:(double)result
{
NSLog(#"result %0.2f",result);
NSDate *date = [NSDate dateWithTimeIntervalSince1970:result];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm:ss"];
NSString *localizedString = [formatter stringFromDate:date];
[formatter release];
return localizedString;
}
Since you have a value that is the number of seconds since midnight, you don't need a date formatter. Try this:
-(NSString*)setHours:(double)result {
int secs = result;
int h = secs / 3600;
int m = secs / 60 % 60;
int s = secs % 60;
NSString *text = [NSString stringWithFormat:#"%02d:%02d:%02d", h, m, s];
}
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
First of all, you have to convert miliseconds in to seconds by dividing miliseconds by 1000.
NSTimeInterval result= 18900/1000;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:result];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSString *formattedDate=[formatter stringFromDate:date];
NSLog(#"Formatted Date : %#",formattedDate);
It's giving you a result for your current time zone, and the time is specified in UTC. So you're an hour after GMT I suppose.
Check out this question: NSDate dateWithTimeIntervalSince1970 NOT returning GMT/UTC time

Resources