Team,
I got response date from server.
"createTime": "2016-10-07T19:22:34.3192343+00:00"
based on date changes i want to check this it on device (mins,hours,days,months years) completed.
Is a way, how to calculate completed time?
based on services request "createTime" : "2016-10-07T19:22:34.3192343+00:00"
Result value should be 30 min. After one hour 1:30 min after 2 days it will be 2 days
NSString* format = #"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
// Set up an NSDateFormatter for UTC time zone
NSDateFormatter* formatterUtc = [[NSDateFormatter alloc] init];
[formatterUtc setDateFormat:format];
[formatterUtc setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Cast the input string to NSDate
NSDate* utcDate = [formatterUtc dateFromString:[formatterUtc stringFromDate:#""2016-10-07T19:22:34.3192343+00:00" "]];
// Set up an NSDateFormatter for the device's local time zone
NSDateFormatter* formatterLocal = [[NSDateFormatter alloc] init];
[formatterLocal setDateFormat:format];
[formatterLocal setTimeZone:[NSTimeZone localTimeZone]];
// Create local NSDate with time zone difference
NSDate* localDate = [formatterUtc dateFromString:[formatterLocal stringFromDate:utcDate]];
NSTimeInterval seconds = [[NSDate date] timeIntervalSinceDate:localDate];
Related
How to convert string date #"2016-10-19T12:37:15.0896144+00:00" int second/Min/hour/days/months/year.
I have date create value i.e #"2016-10-19T12:37:15.0896144+00:00"
**after few seconds need to show " 50 sec"
after few minutes need to show "40 min"
after few hours need to show #"20 hours"
after few days need to show #"3 days"
after few month need to show #"4 month"
after few year need to show #"2 years"**
What I tried is which i not working.
NSString* format = #"2016-10-19T12:37:15.0896144+00:00";
// Set up an NSDateFormatter for UTC time zone
NSDateFormatter* formatterUtc = [[NSDateFormatter alloc] init];
[formatterUtc setDateFormat:format];
[formatterUtc setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Cast the input string to NSDate
NSDate* utcDate = [formatterUtc dateFromString:[formatterUtc stringFromDate:timeString]];
// Set up an NSDateFormatter for the device's local time zone
NSDateFormatter* formatterLocal = [[NSDateFormatter alloc] init];
[formatterLocal setDateFormat:format];
[formatterLocal setTimeZone:[NSTimeZone localTimeZone]];
// Create local NSDate with time zone difference
NSDate* localDate = [formatterUtc dateFromString:[formatterLocal stringFromDate:utcDate]];
NSTimeInterval seconds = [[NSDate date] timeIntervalSinceDate:localDate];
Your input is highly appreciated.
Use NSDateFormatter to convert your strings to dates. Then use NSDateComponentsFormatter with maximumUnitCount of 1 and allowedUnits to include seconds, minutes, hours, days, month, and year.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZ";
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"];
NSDate *date1 = [dateFormatter dateFromString:#"2016-08-19T12:37:15.0896144+00:00"];
NSDate *date2 = [NSDate date]; // or, if date2 is also from a string, just use that dateFormatter again
NSDateComponentsFormatter *componentsFormatter = [[NSDateComponentsFormatter alloc] init];
componentsFormatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
componentsFormatter.allowedUnits = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
componentsFormatter.maximumUnitCount = 1;
NSString *string = [componentsFormatter stringFromDate:date1 toDate:date2];
If you're wondering about the locale setting, see Apple Technical Q&A 1480.
This question already has an answer here:
NSDateFormatter and Time Zone issue?
(1 answer)
Closed 8 years ago.
-(NSTimeInterval)convertStringToDate:(NSString *) date {
NSString *dateString = date;
NSLog(#"dateString = %#", dateString);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy hh:mm a"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *date1 = [[NSDate alloc] init];
date1 = [dateFormatter dateFromString:dateString];
NSLog(#"dateFromString = %#", date1);
NSString *displayDate = [dateFormatter stringFromDate:date1];
NSLog(#"displayDate = %#", displayDate);
return [date1 timeIntervalSince1970];
}
Why I am getting NSTimeInterval with wrong timezone?
You need to read up on the internal representation of NSDates. An NSDate is saved as the number seconds since midnight on 1 Jan, 1984 GMT (The Mac OS X "epoch date") . It represents an instant in time anywhere on the earth, but using a date in GMT as it's "zero date". To display it, you need to convert it to your local time zone.
NSDate has a couple of methods to convert a date to a number: timeIntervalSince1970, which converts an NSDate to the internet standard, which is the number of seconds since Midnight 1 Jan 1970 (The UNIX "epoch date"), and timeIntervalSinceReferenceDate, which converts to the number seconds since the Mac Epoch date.
If you display a date in NSLog:
NSLog(#"Date = %#", someNSDate);
It will be displayed in GMT.
Honestly, it's unclear what you're asking and my best guess is that you just don't understand the classes at play. I've annotated your code in the hope of aiding your comprehension.
Key point: NSDate does not have a time zone. It's an opaque time stamp.
-(NSTimeInterval)convertStringToDate:(NSString *) date {
// log the input string
NSString *dateString = date;
NSLog(#"dateString = %#", dateString);
// create an object that can apply a locale and a time zone in order to
// convert an NSDate to an NSString and vice versa
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy hh:mm a"];
[dateFormatter setLocale:[NSLocale currentLocale]];
// get a date that represents exactly now, for no reason as it's about
// to be thrown away
NSDate *date1 = [[NSDate alloc] init];
// convert to the NSDate that represents the given string.
date1 = [dateFormatter dateFromString:dateString];
// log the converted date. BECAUSE NSDATE DOES NOT HAVE A TIME ZONE,
// it will arbitrarily be displayed in UTC. Because it has to be
// displayed in something
NSLog(#"dateFromString = %#", date1);
// convert date1 back into a printable date; this will again apply
// a time zone and locale
NSString *displayDate = [dateFormatter stringFromDate:date1];
NSLog(#"displayDate = %#", displayDate);
// query the date for "The interval between the date object and
// January 1, 1970 at 12:00 a.m. GMT."; return that
return [date1 timeIntervalSince1970];
}
I was trying to format a time from GMT+7 to GMT+3:
I am building an app with a world clock in specific country (the user will be at the GMT+7and I want to represent the GMT+3 time )
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale];
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800];
NSLocale *USLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setLocale:USLocale];
NSLog(#"Date for locale %#: %#",
[[dateFormatter locale] localeIdentifier], [dateFormatter stringFromDate:date]);
I looked deep into NSDate class reference but I didn't understand how to make it.
Please if someone can help me I will be grateful.
There is 2 important parameters that works separately: Time and Time Zone.
e.g: Vietnam uses GMT+7
If I know that the time in Vietnam is 9:00 AM, then GMT time is 2:00 AM.
When you get the Date from your device you are getting Time and Time Zone: YYYY-MM-DD HH:MM:SS ±HHMM. Where ±HHMM is a time zone offset in hours and minutes from GMT.
Usually you are only using time. However with NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"GMT"] you can tell the NSDateFormatter that you want the GMT time related to your local Time Zone. So, with:
NSDateFormatter *dt = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"GMT"];
[dt setTimeZone:timeZone];
You can get the GMT date of your local time zone date.
So, If you have GMT+7: 9:00 AM and you want to print out GMT+3: 5:00 AM, you have 3 possibilities:
NSDate *localDate = [NSDate date];
OPTION 1
Add a time interval of -4 hours:
NSTimeInterval secondsInFourHours = -4 * 60 * 60;
NSDate *dateThreeHoursAhead = [localDate dateByAddingTimeInterval:secondsInFourHours];
NSDateFormatter *dt = [[NSDateFormatter alloc] init];
[dt setDateFormat:#"h:mm a"];
NSLog(#"GMT+7(-4) = %#", [dt stringFromDate:dateThreeHoursAhead]);
This is the easiest way to do it. If you are always at GMT+7 and you need GMT+3, this is a time interval of -4 hours.
OPTION 2
Set the time to GMT time zone and then add a +3hours time interval. The easiest way to do it is to add the 3 hours first and then move the time to GMT:
NSTimeInterval secondsInThreeHours = 3 * 60 * 60;
NSDate *dateThreeHoursAhead = [localDate dateByAddingTimeInterval:secondsInThreeHours];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"GMT"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"h:mm a"];
NSString *date = [dateFormatter stringFromDate:dateThreeHoursAhead];
NSLog(#"GMT+3 = %#", date);
OPTION 3
This is the better option. GMT+3 is EAT (East Africa Time) you can set your time zone to EAT with: [NSTimeZone timeZoneWithName:#"EAT"]
NSDateFormatter *dt = [[NSDateFormatter alloc] init];
[dt setDateFormat:#"h:mm a"];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"EAT"];
[dt setTimeZone:timeZone];
NSLog(#"EAT = %#", [dt stringFromDate:localDate]);
Option 3 is always retrieving GMT+3
An example code here.
I have two strings coming from my server in which I store the time, and I need to compare the time interval between those two, in minutes, and if it's necessary, in hours. Should I convert to NSDate or use NSString?
The NSStrings look like:
NOW 14:22
LAST TIME 10:18
EDIT #1
Since everyone is saying me to use NSDate, i converted the data in my database to DATETIME, and now i can compare the two NSDate using the following code :
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"pt_BR"]];
[dateFormatter setDateFormat: #"yyyy-MM-dd HH:mm:ss"];
NSDate *currentDateTimeWithOffset = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone localTimeZone] secondsFromGMT]];
NSString *strDate = [dateFormatter stringFromDate:currentDateTimeWithOffset];
NSDate * now = [dateFormatter dateFromString:strDate];
NSDate *date = [dateFormatter dateFromString:#"2013-04-09 12:10:18"];
NSLog(#"Difference %f",[now timeIntervalSinceDate:date]);
And the result is the following :
Difference 864.000000
NOW 2013-04-09 15:24:42 +0000
LAST DATE 2013-04-09 12:10:18
Is that correct? the Difference is in Seconds?
If the format gets more complex than the one you've shown, consider using NSDateFormatter. For the simple example:
NSArray *hoursMins = [timeString componentsSeparatedByString:#":"];
NSInteger timeInMins = [hoursMins[0] intValue] * 60 + [hoursMins[1] intValue];
Then subtract the two times in minutes. The date formatter approach looks like this:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm"];
NSDate *date = [df dateFromString:timeString];
You can get a difference in seconds between two dates using:
[date timerIntervalSinceDate:anotherDate];
NSDateFormatter is the "clean" way to do it. But if you are looking for quick and dirty, and those are the actual strings you are getting (that include the NOW and LAST TIME), I'd just use a specific NSRange to pull the hours and minutes out and compare them.
Make sure, though that you check the hours, and if the "now" hour is before the "last time" hour, you add 24 to the now to throw in the day rollover.
With only NSString, NSDateFormatter is used to get NSDate
NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];
If you had separate values for hours, minutes and seconds you could use NSCalendar
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:1965];
[comps setMonth:1];
[comps setDay:6];
[comps setHour:14];
[comps setMinute:10];
[comps setSecond:0];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];
And a perfect solution would be to use timestamps instead of NSString. Not only it's easy to convert timestamps to NSDate (NSDate +dateWithTimeIntervalSinceReferenceDate)and then to NSString when needed, but you can also get the time difference by subtraction.
And with two NSDate objects the time difference is calculated with NSDate -timeIntervalSinceDate.
This question already has answers here:
NSDate is not returning my local Time zone /default time zone of device
(7 answers)
Closed 9 years ago.
I am using the datepicker for picking the time but after sending to the server when I am retrieving back then its showing 5-6 hour difference.
Server hosted in USA.
So how I will do it accurately without any difference, User do request from any where.
Thanks,
Arun
UTC is standard time zone to be used. Following is the code to get date in UTC
+(NSString *)getCurrentTime{
NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-ddHH:mm:ss"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
NSString *dateStr = [dateFormat stringFromDate:date];
RELEASE_OBJECT(date)
RELEASE_OBJECT(dateFormat)
return dateStr;
}
Send the date with the timezone. For example:
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
NSDate *date = [formatter dateFromString:dateString];
Will include the timezone and the server will be able to translate to its own timezone.
We use the ISO 8601 for better compatibility. There are also NSFormatter subclasses that to convert from ISO 8601 to NSDate and back (like this).
It is time zone issue. You can use [yourDate dateByAddingInterval:[NSTimeZone secondsFromGMT]]; .
Please try to set the Locale for the time:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd MM yyyy hh:mm:ss"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"] autorelease]];
NSDate* sourceDate = [dateFormatter dateFromString:dateString];
//Timezones
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"UTC"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
//Interval in Timezones
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
//converted date
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] ;
NSString *strFinalDate = [dateFormatter stringFromDate:destinationDate];
[dateFormatter release];
[destinationDate release];
If you are sending your iPhone default times to server and server is also sending the same time which you have send it then it will be problem of the converting your NSDate to NSString with NSDateFormatter with some different timezone.
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
Use above code when you using NSDateFormatter.