Store UTC date from server in NSDate object - ios

I receive UTC date from server as 2015-10-07 17:43:11. I want to store this date in NSDate object. I do following code:
NSString *dateFromServer = #"2015-10-07 17:43:11";
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [[NSDate alloc] init];
date = [formatter dateFromString:dateFromServer];
NSLog(#"%#", date);
This gives me result as:
2015-10-07 12:13:11 +0000
(I stay in GMT+05:30 zone). How can I store my UTC time (which I receive from the server)directly into the NSDate object?

There are 2 possible solutions:
1. Have the server send the time zone embedded in the date string:
"2015-10-07 17:43:11 UTC"
then parse it with the appropriate date format which will always give you the correct time zone.
2. Otherwise, you'll have to explicitly tell the formatter what is the time zone of the string or it'll use the current time zone of the device by default.
let dateFromServer = "2015-10-07 17:43:11"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = NSTimeZone(abbreviation: "UTC")
if let date = formatter.dateFromString(dateFromServer) {
print(date) // "2015-10-07 17:43:11"
}
Note:
The NSDate object does not have a time zone - dates are universal and indicate a point in time. To display a date with a time zone you use a formatter to create a locale sensitive string.
Also there's no need to do this:
NSDate *date = [[NSDate alloc] init];
This creates a new date object with the current time. You're overriding this value in the next line.

Try like this ;
NSString *dateFromServer = #"2015-10-07 17:43:11";
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [[NSDate alloc] init];
date = [formatter dateFromString:model.start_time];
NSLog(#"%#", date);

NSDate *currentDate = [[NSDate alloc] init];
Now it is in UTC, (at least after using the method below)
To store this time as UTC (since refernce date 1970) use
double secsUtc1970 = [[NSDate date]timeIntervalSince1970];
Set Date formatter to output local time:
NSTimeZone *timeZone = [NSTimeZone defaultTimeZone];
// or specifc Timezone: with name
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString *localDateString = [dateFormatter stringFromDate:currentDate];
A NSDate object always uses UTC as time reference, but the string representation of a date is not neccessarily based on UTC timezone.
Please note that UTC is not (only) a timeZone, It is a system how time on earth is measured, how it is coordinated (The C in UTC stands for coordinated).
The NSDate is related to a reference Date of midnight 1.1.1970 UTC, altough slightly wrongly described by Apple as 1.1.1970 GMT.

You don't need to covert anything, you only need to consider how to display date in UI, because 2015-10-07 12:13:11 +0000 and 2015-10-07 17:13:11 UTC + 5 are the same NSDate instances.
So if you want to get string representation of the NSDate instance retrieved from server in your local timezone, Just do this.
NSDateFormatter * formatter = [NSDateFormatter new];
formatter.timeStyle = NSDateFormatterStyleMediumStyle;
formatter.dateStyle = NSDateFormatterStyleMediumStyle;
...
You can find more informations about how to format date/time in apple docs.

Related

How can I get the Correct Current Time in iOS?

I know this it the repeated question. I have reviewed many answers but still didn’t get any solution.
My question is,
How can I get the Time of Device if user have set it manually..?
I have implemented one chatting app. But in this app, I have issues of timings. If user have set manually time then how can we identify that.?
I want to get correct current UTC time. So using this, I can identify the difference between device time and UTC time.
If we are using, NSDate *currentDateAndTime = [NSDate date];, then it returns only UTC time according to device, not the current UTC time.
Is there any easy way to find out this solution?
Any help would be appreciated.
There is no trusted time source in iOS. You just operate with monotonic and non-monotonic time.
Monotonic time (or absolute time) represents the absolute elapsed wall-clock time since some arbitrary, fixed point in the past. The CACurrentMediaTime() or mach_absolute_time return monotonic time.
Non-monotonic time represents the machine's best-guess as to the current wall-clock, time-of-day time. It can jump forwards and backwards as the system time-of-day clock is changed. The [NSDate date] call returns it.
As an option, you can take the trusted date/time from the http Date response header. Then save it and current monotonic time(CACurrentMediaTime()) in the keychain.
Here is the way to get the current trusted time:
last known online time + (CACurrentMediaTime() - saved monotonic time)
Another solution would be to use NTP server.
This might solve your problem
NSDate * date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
NSString *currentTime = [dateFormatter stringFromDate:date];
NSLog(#"current time is:%#",currentTime);
use this code it helps you
NSDate * datee = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString *localDateString = [dateFormatter stringFromDate:currentDate];
NSLog(#"%#",localDateString);
Use : NSDate *currentDateAndTime = [NSDate date];
This will get you the absolute date and time in GMT reference zone.
Try this:
swift:
let date = NSDate()
let dateFormatter = NSDateFormatter()
let timeZone = NSTimeZone(name: "UTC")
dateFormatter.timeZone = timeZone
println(dateFormatter.stringFromDate(date))
Obj-C:
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:timeZone];
NSLog(#"%#", [dateFormatter stringFromDate:date]);
You can use this code for getting current time:-
Swift 3
let date = Date()
let formatter = DateFormatter()
formatter.timeZone = TimeZone(abbreviation: "GMT+0:00") //Current time zone
formatter.dateFormat = "HH:MM a"
let currentTime: String = formatter.stringFromDate(date)
print("My Current Time is \(currentTime)")
Result **
Output : - "My Current Time is 11:05 AM\n"

Need assistance regarding NSTimeInterval and timezone [duplicate]

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];
}

NSDateFormatter return Date in GMT specific timezone

I want to get the date and time in a specific time zone. I am getting most of the things right but just at the end when i get the date from NSString using NSDateFormatter method it returns me the date in the GMT specific time zone. The method [formatter stringFromDate:gmtDate]; return me the expected date and time. The problem happen when i get the date from the string i-e when i execute this method self.localTime = [formatter dateFromString:str];. self.localTime is a NSDate property in my class.
So when i print the str it gives me the date and time in that specific time zone which is represented as self.timeZoneID, which is also a property on my class
NSDate *gmtDate = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:self.timeZoneID]];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *str = [formatter stringFromDate:gmtDate];
NSLog(#"Date string : %#", str);
self.localTime = [formatter dateFromString:str];
Any idea that what could be the reason that i am getting the right string output but when i assign it to my property localTime it give me the time in GMT
Reason is that NSDate have a default time zone that is GMT for consideration and when a user wants to have time specific for some time zone then NSDateFormatter provides way to set specific time zone which you are using for gmtDate object and not for self.localTime(this is taking GMT ,default time zone).

Converting UTC time to local time

I am fetching data from the server and part of that data is time. Time is stored in UTC in my DB so what I'm returning is also in UTC. For example: 2014-05-22 05:12:40
Further, I am using the DateTools to show the time difference on the device like X hours ago or X minutes ago etc....
The problem is that when the UTC time coming from the server is compared to the local time there is a huge difference. Something that should say X seconds ago says X hours ago because of the time difference.
Question
How can I convert the date coming from the server to the local time zone set on the device?
This is what I'm doing right now:
#date_formatter = NSDateFormatter.alloc.init
#date_formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
#date_from_server = "2014-05-22 05:12:40"
#date = #date_formatter.dateFromString(#date_from_server)
#time.text = #date.shortTimeAgoSinceNow
I don't know how it is done in ruby motion but in Objective-C, it is done as follows :
1.) Create an instance of NSDateFormatter class
2.) Set a specific date format string of it, and also you set the specific time zone of it
3.) Get a date from the incoming string via the dateformatter instance
4.) Change the time zoneof the date formatter instance to the local time zone
5.) Convert the date obtained previously to the new time zone .
In Objective-C
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:incomingDateFormat];
[df setTimeZone:incomingTimeZone]; // Can be set to #"UTC"
NSDate *date = [df dateFromString:incomingDateString];
[df setDateFormat:newDateFormat];
[df setTimeZone:newTimeZone]; //// Can be set to [NSTimeZone localTimeZone]
NSString *newDateStr = [df stringFromDate:date];
I believe the same can be done in Rubymotion too.
NSDateFormatter *formater = [[NSDateFormatter alloc] init];
formater.dateFormat = #"yyyy-MM-dd HH:mm:ss";
NSString *datestr = #"2014-05-22 05:12:40";
formater.timeZone = [NSTimeZone localTimeZone];
NSDate *date = [[formater dateFromString:datestr] dateByAddingTimeInterval:formater.timeZone.secondsFromGMT];
NSDateFormatter *df=[[[NSDateFormatter alloc] init] autorelease];
// Set the date format according to your needs
[df setTimeZone:[NSTimeZone timeZoneWithName:#"America/Toronto"]];
//[df setDateFormat:#"MM/dd/YYYY HH:mm "] // for 24 hour format
[df setDateFormat:#"YYYY-MM-dd HH:mm:ss"];// for 12 hour format
Try this

Objective-C, How can I get the current date in UTC timezone?

I am trying:
NSDate *currentDateInLocal = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:SS.SSS'Z'"];
NSString *currentLocalDateAsStr = [dateFormatter stringFromDate:currentDateInLocal];
NSDateFormatter * dateFormatter2 = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter2 setTimeZone:timeZone];
[dateFormatter2 setDateFormat:#"yyyy-MM-dd'T'HH:mm:SS.SSS'Z'"];
NSDate *currentDateInUTC = [dateFormatter2 dateFromString:currentLocalDateAsStr];
but It's still does not represent the current UTC time, how can I achieve this?
Thanks
You're overcomplicating things.
NSDates don't have time zones or calendars. [NSDate date] gets the current date, which is a measurement of a moment in history. If I run [NSDate date] in Europe at exactly the same time as you run it in America then we'll get exactly the same value.
How you print a date depends on the calendar and the time zone. So a date printed in the Gregorian calendar looks different from the same one printed in the Julian calendar. And a date printed in the UTC Gregorian calendar looks different from the same one printed in the PST Gregorian calendar. But they're still the same date.
So you want to jump straight to your dateFormatter2.
The accepted answer by Alex Wien is incorrect.
By default, NSDateFormatter adjusts the NSDate’s date-time value from UTC to the user's local time zone. To prevent that adjustment, tell the NSDateFormatter to use the time zone for UTC.
To verify results, google "current time utc".
My source code below should do the job, meaning get the current date-time as a string in ISO 8601 format in the UTC (Zulu) time zone signified by a Z on the end.
NSDate* datetime = [NSDate date];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]]; // Prevent adjustment to user's local time zone.
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString* dateTimeInIsoFormatForZuluTimeZone = [dateFormatter stringFromDate:datetime];
You could put this logic in a pair of convenience methods somewhere in your app.
- (NSString*)now
{
// Purpose: Return a string of the current date-time in UTC (Zulu) time zone in ISO 8601 format.
return [self toStringFromDateTime:[NSDate date]];
}
…and…
- (NSString*)toStringFromDateTime:(NSDate*)datetime
{
// Purpose: Return a string of the specified date-time in UTC (Zulu) time zone in ISO 8601 format.
// Example: 2013-10-25T06:59:43.431Z
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString* dateTimeInIsoFormatForZuluTimeZone = [dateFormatter stringFromDate:datetime];
return dateTimeInIsoFormatForZuluTimeZone;
}
Example of usage…
NSString* now = [self now];
Or turn those minus signs into plus signs to use as class methods rather than instance methods…
NSString* now = [SomeClassNameHere now];
Tip: For better readability by humans, change that T in the format to a SPACE. For better interoperability by software, keep the T. The ISO 8601 spec tolerates a space but recommends keeping the T.
Tip: I've not tested, but… Some people say instantiating [NSDateFormatter][4] is expensive. If doing so often (such as in a loop) consider caching a single instance for re-use.
NSDate *currentDate = [[NSDate alloc] init];
Now it is in UTC, (at least after using the method below)
To store this time as UTC (since refernce date 1970) use
double secsUtc1970 = [[NSDate date]timeIntervalSince1970];
Set Date formatter to output local time:
NSTimeZone *timeZone = [NSTimeZone defaultTimeZone];
// or Timezone with specific name like
// [NSTimeZone timeZoneWithName:#"Europe/Riga"] (see link below)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString *localDateString = [dateFormatter stringFromDate:currentDate];
Available NSTimeZone names
A NSDate object always uses UTC as time reference, but the string representation of a date is not neccessarily based on UTC timezone.
Please note that UTC is not (only) a timeZone, It is a system how time on earth is measured, how it is coordinated (The C in UTC stands for coordinated).
The NSDate is related to a reference Date of midnight 1.1.1970 UTC, altough slightly wrongly described by Apple as 1.1.1970 GMT.
In the original question the last word timeZone is not perfect.
PLEASE SET UP Calendar Identifier !!!
I am not too late! Because I saw no one set up the Calendar Identifier. It is really important for worldwide users. Many users using a non-Gregorian calendar. They will get wrong year string. Especially, when you need store it into your own database. (We met this problem before)
NSCalendarIdentifierGregorian
NSCalendarIdentifierBuddhist
NSCalendarIdentifierChinese
NSCalendarIdentifierHebrew
NSCalendarIdentifierIslamic
NSCalendarIdentifierIslamicCivil
NSCalendarIdentifierJapanese
NSCalendarIdentifierRepublicOfChina
NSCalendarIdentifierPersian
NSCalendarIdentifierIndian
NSCalendarIdentifierISO8601
Code:
-(NSString *)getUTCFormateDate:(NSDate *)localDate
{
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormatter setCalendar:gregorianCalendar];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setLocale:locale];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:localDate];
return dateString;
}
Swift 3
let utcTimestamp = Date().timeIntervalSince1970
print("timeStamp = \(utcTimestamp)")
May following extension would be easier.
Swift 4: UTC/GMT ⟺ Local (Current/System)
extension Date {
// Convert local time to UTC (or GMT)
func toGlobalTime() -> Date {
let timezone = TimeZone.current
let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
// Convert UTC (or GMT) to local time
func toLocalTime() -> Date {
let timezone = TimeZone.current
let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
}
// Try it
let utcDate = Date().toGlobalTime()
let localDate = utcDate.toLocalTime()
print("utcDate - (utcDate)")
print("localDate - (localDate)")
[NSDate date] is UTC. Maybe you get fooled by looking in the locals? Then it gets converted to your timezone.
If you see the value in the locals, you see it in local time, but if you print it in the console, you see it in UTC.
When you see '+0000' after the time, you know it is in UTC
Still another way to do it is like so in a C++ class in your Objective C project. (So, make a .mm file and build a C++ class with public and private parts, and stick this in the public part (unless you need it private).) Then, reference it like NSString *sNowUTC = MyClass::getUTCTimestamp();.
static NSString *getUTCTimestamp(){
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time (&rawtime);
timeinfo = gmtime (&rawtime);
// make format like "2016-06-16 02:37:00" for
// June 16, 2016 # 02:37:00 UTC time
strftime (buffer,80,"%F %T",timeinfo);
std::string sTime(buffer);
NSString *sUTC = #(sTime.c_str());
return sUTC;
}
This is what i used.
static func makeISO8601Date(isoDateString: String) -> Date {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter.date(from: isoDateString)
}
makeISO8601Date(isoDateString: "2017-12-31T23:59:59+00:00")

Resources