JSON date string conversion issue in iOs - 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;

Related

Timezone issue when date display in UI(show 1 day lesser) in Objective C

I am facing one problem, which is related to different timezone.
In UI I have set the date with 3/11/18
leaveEndDate -> 3/11/18
in service I get result.
leaveEndDate = "2018-03-11T06:00:00Z";
But when I display the date in UI, its showing "3/10/18" but actual result should be "3/11/18"
It display 1 day lesser in the application.
I have change the Time Zone is -> Washington, DC - United States and it should work for all timezones.
Approach
//Adjust the dates.
NSDate* originalDateValue = [self valueForKey:actualKey];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ss Z"; // tried formatter-> #"yyyy-MM-dd'T'HH:mm:ss'Z'"; // yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
NSString *dateString = [dateFormatter stringFromDate:originalDateValue];
dateFormatter.timeZone = [NSTimeZone localTimeZone];
NSDate * actualDate = [dateFormatter dateFromString:dateString];
[self setValue:actualDate forKey:actualKey];
Another approach which I used is:
//Adjust the dates.
NSDate* originalDateValue = [self valueForKey:actualKey];
NSDate* adjustedDateValue = [self.class adjustDate:originalDateValue forTimezone:[self timeZoneName]];
+(NSDate*)adjustDate:(NSDate*)originalDateValue forTimezone:(NSString*)timezoneName
{
if([originalDateValue isEqual:[NSNull null]]) return nil;
NSTimeInterval timeInterval = ([[NSTimeZone timeZoneWithName:timezoneName] secondsFromGMTForDate:originalDateValue] - [[NSTimeZone localTimeZone] secondsFromGMTForDate:originalDateValue]);
NSDate* adjustedDateValue = [originalDateValue initWithTimeInterval:timeInterval sinceDate:originalDateValue]; //[originalDateValue dateByAddingTimeInterval:timeInterval];
return adjustedDateValue;
}
Third approach
NSDate* originalDateValue = [self valueForKey:actualKey];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"]];
NSString *dateString = [dateFormatter stringFromDate:originalDateValue];
NSDate* adjustedDateValue = [dateFormatter dateFromString:dateString];
Any help?
originalDateValue is always being set to UTC time for the date you are giving it. NSDate works on UTC time since you aren't specifying a timezone. dateFormatter is converting the input you're giving it to your localtime, which is several hours behind. Since you don't specify a time, it's setting the time to 00:00:00 midnight, so when converting fro UTC to Washington DC, you're adjusting the timezone several hours behind.
You must adjust the source date according to the offset from UTC to localTimeZone:
NSInteger sourceUTCOffset = [sourceTimeZone secondsFromGMTForDate:originalDateValue];
NSInteger destinationUTCOffset = [localTimeZone secondsFromGMTForDate:originalDateValue];
NSTimeInterval interval = destinationUTCOffset - sourceUTCOffset;
NSDate destinationDate = [initWithTimeInterval:interval sinceDate:originalDateValue];
Then operate on destinationDate the way you have already provided.

Getting one hour difference on date

Following is the code I am writing to convert UTC time to local time :
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormatter1 setLocale:locale];
NSDate *date = [dateFormatter1 dateFromString:dateString];
dateString = [date descriptionWithLocale:[NSLocale systemLocale]];
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date];
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:#"HH:mm"];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
dateString = [dateFormatters stringFromDate: destinationDate];
But this way I am getting a difference of 1 hour. i.e. if date displayed on web app is 12:30, on the app it is displayed as 13:30. Why is that so ?
Try with this code:
- (NSDate *) UTCTimeToLocalTime
{
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = [tz secondsFromGMTForDate: yourDate];
return [NSDate dateWithTimeInterval: seconds sinceDate: yourDate];
}
- (NSDate *) LocalTimeToUTCTime
{
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = -[tz secondsFromGMTForDate: yourDate];
return [NSDate dateWithTimeInterval: seconds sinceDate: yourDate];
}
You need to learn and accept the principles of handling times and dates.
NSDate represents points in time, independent of any time zone. If we are talking on the phone, and our computers calculate [NSDate date], they get the exact same date, even if our watches display totally different times.
Calendars with time zone information transform between NSDate and something that a user in one particular part of the world expects. So the same NSDate is converted to a string to match what your watch displays, or what my watch displays, which would be different. There should be no need to modify an NSDate in any of this, as you did.

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

Time difference between 2 dates results in wrong or unknown values

I am trying to find the time difference between 2 dates. but i am getting values as -0.0000, nan, or -357683564. below is my code to find time difference. am i doing any wrong in this calculations ?
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeStyle = NSDateFormatterNoStyle;
formatter.dateFormat = #"YYYY-MM-dd HH:MM:SS ±HHMM";//MM/dd/yyyy
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[formatter setLocale:usLocale];
NSDate *intialTime= [formatter dateFromString:[NSString stringWithFormat:#"%#",[dateArray objectAtIndex:i]]];//[formatter dateFromString:#"12/11/2005"];
NSDate *presentDate = [NSDate date];
NSTimeInterval timeInterval = [presentDate timeIntervalSinceDate:intialTime];
int seconds = (int)ceil(timeInterval);
int mins = seconds / 60;
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = timeInterval / secondsInAnHour;
NSLog(#"Time interval in Mins:%d -- %.4f -- %d",mins,timeInterval,hoursBetweenDates);
In Log :
Time interval in Mins:-35791394 -- nan -- -2147483648
intialTime - (null) and presentDate - 2014-05-09 10:30:15 +0000
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setLocale:[NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"]];
NSDate *dateToday = [NSDate date];
NSString *date = #"09-05-14"; // Put your initial date here...
[df setDateFormat:#"HH:mm:ss"];
NSString *todayString = [df stringFromDate:[NSDate date]];
NSString *todaysDateTime = [date stringByAppendingString:todayString];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *initialDate = [df dateFromString:todaysDateTime];
NSTimeInterval ti = [initialDate timeIntervalSinceDate:dateToday];
I fixed my Issue by using NSTimeZone. here was my problem.it was displaying date as their server date and my current date was not matching to timezone and not able to format it. Thanks for you all friends for helping me to find my mistake.
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"EST"];
[dateFormatter setTimeZone:gmt];

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

Resources