Changing timezones in a textbox - iphone

I have a small IOS program and that get a time from a database server. I would like to convert that to the users localtime (I always know the timezone of the server).
I have been playing with replacing the hour piece of the string, but that seems like a bad idea.
In C# I would convert the string into a DateTime and add the hours in the diference between the server time and the localtime, but I simply cant figure out how to do that in ObjectiveC.
So could anyone give a few hints? The date/time string I get from the sever looks like this:
2011-02-27 12:10:02

I would convert the date from the string into and NSDate object using NSDateFormatter. The you can use the dateByAddingTimeInterval method to add in your hour. Also NSCalendar has more advanced functions for adding time intervals.

I believe this should work for local time:
NSDateFormatter *dateFormatter = [NSDateFormatter alloc] init];
NSLocale *serverLocale = [NSLocale alloc] initWithLocaleIdentifier:#"en_US"];//Change to Server Locale
[dateFormatter setLocale:serverLocale];
[serverLocale release];
[dateFormatter setDateFormat:#"YYYY-MM-DD HH:MM:SS"];
NSDate *date = [dateFormatter dateFromString:#"2011-02-27 12:10:02 "];
//Replace the locale below with what you need
NSString *dateString = [date descriptionWithLocale:[NSLocale currentLocale]];
[dateFormatter release];
textField.text = dateString;

Related

Conversion from NSString to NSDate doesn't work

I have to convert this NSString: "12/13/1980" to a NSDate object.
I use a code like this:
NSString *birthday = #"12/13/1980"
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy"];
NSDate *date = [dateFormat dateFromString:dateString];
But the result is this: "1980-12-12 23:00:00 +0000"
Why? I'd like the same format and the same date.
Thank you very much.
The [dateFormat dateFromString:dateString] method produces an NSDate object which represents a single point in time.
When you NSLog a date object, it is printing a system representation of the NSDate object. I'm assuming your locale is GMT+1 .. so the NSLog prints 12/12/1980 23:00.
If you want to print the date object back, use your formatter to do [dateFormat stringFromDate:date];
It's because a NSDate object has always to have a time and a timezone, so if you don't specify that in your the string you're trying to convert IOS will use your local timezone and then guess the time, wich in this case will be 23:00 in UTC 0
The format is dependent on the localisation, there's also the option to set whether the date/time is short, medium or long format - I believe short is what you're looking for:
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html

Why does my NSDateFormatter sometimes return an a.m. or p.m. with yyyyMMddHHmmssSSS?

Sometimes my code is returning an a.m. or p.m. but not always. Most of the time it just returns what I expect, which is something like: 20110815170852164
But other times it's returning: 20100412010241 a.m.450
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyyMMddHHmmssSSS"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
What could be causing this? Specific date/time country settings on users iPhones? I have this out to thousands of people, and most aren't returning the a.m. (which is expected) but others are. WHY?
The problem you are describing is a known bug. Check out some discussion on the problem on stackoverflow, and you can find some possible work-arounds there.
Here's an excerpt of huyz's explaination of the bug:
The problem comes from NSDateFormatter somehow “getting stuck” in the 12 or 24-hour time mode that the user has manually selected. So if a French user manually selects 12-hour mode, and the application requested NSDateFormatter to output time with the 24-hour format “HHmm”, it would actually receive time in a 12-hour format, e.g. “01:00 PM”, as if the application had instead requested “hhmm aa”. The reverse would happen if a US user manually selected 24-hour mode: outputting time with the 12-hour format “hhmm aa” would actually get you time in the 24-hour format instead, e.g. “17:00″.
Right. The solution is to explicitly set the locale of the date formatter, ideally to en_US_POSIX. See the final answer to this question.
I was working on a data-share function of a project which was highly depending on the values/results entered in advance when I bumped into the same problem. I implemented a nasty little workaround for saving the right datetime in 24h format to the database.
The solution is very simple
First, I get the local date from the device:
NSDate* now = [NSDate date];
Second step is to create a NSDateFormatter with US locale regardless of system's locale to make sure that "PM" is going to be "PM":
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]];
Then, I get the date (year, month, day) into a string:
[formatter setDateFormat:#"yyyy-MM-dd"];
NSString *date = [formatter stringFromDate:now];
For the next part, I get the hours, minutes and seconds:
[formatter setDateFormat:#"hh"];
NSString *hours = [formatter stringFromDate:now];
[formatter setDateFormat:#"mm"];
NSString *minutes = [formatter stringFromDate:now];
[formatter setDateFormat:#"ss"];
NSString *seconds = [formatter stringFromDate:now];
Next, I get the part of the day:
[formatter setDateFormat:#"a"];
NSString *partOfDay = [formatter stringFromDate:now];
Then comes the logic: if the part of the day is PM but the hours are less then 12, we just have to correct that. In code:
if([partOfDay isEqualToString:#"PM"] && [hours intValue] < 12) {
hours = [[NSString alloc] initWithFormat:#"%i", ([hours intValue] + 12)];
}
After this modification, we are ready to put the string together in order to have a datetime ready to be saved into SQL:
NSString *sqlDateTime = [[NSString alloc] initWithFormat:#"%# %#:%#:%#", date, hours, minutes, seconds];
That's all there is to it. And from now we can only hope that Apple is going to fix this bug to make it work as it should be.
I hope this helps.

is there any easy way to get Date?

I'm new to iPhone development. I want to set default date to NSDate Object as string. I don't see any easy way or method...
I think there might be a method in NSCalender? If there's such a method, please tell me.
Thanks in advance.
I'm not totally clear on what you are asking, but to create an instance of an NSDate object with the current date, one calls:
NSDate * myDate = [NSDate date];
If you are saying that you have a c-string or NSString that needs to be parsed to initialize an NSDate object, that's another question.
I have some code posted here:
How get a datetime column in SQLite with Objective C
that shows how to create NSDates from NSStrings using NSDateFormatter.
If you want to create an NSDate from a string, you need to use an NSDateFormatter to do it. It's important to note that the formatter will use the current locale's time zone when constructing the date, unless you put a time-zone in as part of the format. For more information about constructing time zones, see NSTimeZone.
For example, to create a date using the ubiquitous format '2011-01-16 00:00' in UTC, you would do:
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm"];
// Only certain abbreviations are okay, like UTC. See docs for more info
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
NSDate* midnight_26_jan_2011_utc = [formatter dateFromString:#"2011-01-26 00:00"];
// this will display in your system locale
// (for me, it shows 2011-01-25 19:00 +0500 because I'm America/New_York time)
NSLog(#"date: %#", midnight_26_jan_2011_utc);
[formatter release];
Edit: Added time to format string.
You will need to look at the NSDate and NSDateFormatter classes. Here's a simple example of how to use them:
NSString* defaultDateString = [NSString stringWithFormat:#"2011-01-22 15:30:00"];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate* defaultDate = [dateFormatter dateFromString:defaultDateString];
[dateFormatter release];
and if you wanted to get the string from a date you can just use:
NSString* defaultDateString = [dateFormatter stringFromDate:defaultDate];
NSDateFormatter *DateFormatter=[[NSDateFormatter alloc] init];
[DateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
[DateFormatter setDateFormat:#"yyyy-MM-dd hh:mm:ss"]; //here,you can set the date format as you need
NSDate *now = [[[NSDate alloc] init]autorelease];
NSString *theDate = [DateFormatter stringFromDate:now];
Now, you can use the string the date. :)
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]init]autorelease];
[dateFormatter setDateFormat:#"yyyy-mm-dd"];
NSDate *yourDate = [dateFormatter dateFromString:#"2011-01-26"];

Can I use NSDateFormatter to convert this date string to an NSDate?

I have this string...
2010-08-24T16:00:00-05:00
and I'd like to extract the time portion from it (i.e. 16:00) and convert it to its 12-hour equivalent (i.e. 04:00 pm). I'm trying to use NSDateFormatter to accomplish this, but it's not working...
NSDateFormatter* dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:#"hh:mm a"];
NSDate *date1 = [dateformatter dateFromString:[listOfTimes objectAtIndex:0]];
[dateformatter release];
Can I use NSDateFormatter with this date format? If not, how can I extract the time and convert it to its 12-hour time equivalent?
Thanks!
The problem has to do with parsing the colon. I asked the same question and the solution is here: How to parse a date string into an NSDate object in iOS?
I think you should be able to do something like the following.
// create the date formatter object
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSDate* date = [formatter dateFromString:dateString];
// set up the new date format
[formatter setDateFormat:#"hh:mm:ss"];
NSString *twelveHourTime = [formatter stringFromDate:date];
[formatter release];
Update: Fixed the dateFormatter string format. I had the line below, but the Z seems to be unnecessary. Timezones always screw me up. :-/
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZ"];
This answer needs to be updated. As of iOS 10 the system provided NSISO8601DateFormatter is available for this particular format.

NSDateFormatter dateFromString and iPhone in 24 Hour Format Confusion

I'm having a problem. I get incoming time strings in 12-hour format, and I'm turning them into NSDate objects. When the iPhone is in 12 hour format, no problem. But when it's in 24 Hour format, things go wrong. Here's some sample code to demonstrate:
NSString *theTime = #"3:19 PM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"h:mm a"]; // "3:19 PM"
NSDate *date = [formatter dateFromString:theTime];
NSString *theString = [formatter stringFromDate:date];
In 24 hour mode, date is 1970-01-01 03:19:00, and theString is "3:19" - WRONG
In 12 hour mode, date is 1970-01-01 15:19:00, and theString is "3:19 PM" - RIGHT
So... question 1: why is the device's 24 hour setting overriding my date formatter setting?
and more importantly, question 2: How do I get a proper conversion from 12 hour time to 24 hour time?
I already have code to detect if the phone is in 24 hour mode, but other than digging around in the string and swapping the 3 with a 15, there doesn't seem to be a clean way to do this.
Not sure if you still need it, but I've had a similar problem which got solved by setting the locale for the date formatter. That is, if you want to force it to 12-hour mode, regardless of the user's 24/12 hour mode setting, you should set the locale to en_US_POSIX.
The reason for this behaviour is Locale, set the correct Locale
NSString *strAgendaDate = #"01/17/2012 12:00 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"] autorelease];
[dateFormatter setDateFormat:AgendaDateFormatForMeeting];
NSDate *meetingDate = [dateFormatter dateFromString:aStrDate];
[dateFormatter setDateFormat:AgendaDateRepresentation];
strAgendaDate = [dateFormatter stringFromDate:meetingDate];
It works for both 24-hour and 12 hour format
I believe the #"h:mm a" should be #"HH:mm a".
If you use the pre-build dateformatter in cocoa, everything will be taken care of for you.
NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc] init] autorelease];
[timeFormatter setTimeStyle:NSDateFormatterShortStyle];
[timeFormatter setDateStyle:NSDateFormatterNoStyle];
NSDateFormatterShortStyle and NSDateFormatterNoStyle comes in different varieties.
Using those will make sure you respect the settings the user has selected for dates and times.
The 12-14 hour clock conversion is taken care of by the SDK, if you have a model or some value object for storing your dates try to keep them as NSDate. This way you can format them only when you need to display them. Saving dates as strings could open a world of trouble when you maybe parse them from xml where the GMT is specified separately or try to add and subtract NSTimeIntervals.
I changed from #"hh:mm:ss" to #"HH:mm:ss" and time style was changed from "1:03 PM" to "13:03".
Hope this will help you.
Okay, I left a comment, but it squished all the code together, so I'll have to "answer" my question with a comment:
Thanks. I gave it a whirl with this code:
NSString *theTime = #"3:19 PM";
NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc] init] autorelease];
[timeFormatter setTimeStyle:NSDateFormatterShortStyle];
[timeFormatter setDateStyle:NSDateFormatterNoStyle];
NSDate *date = [timeFormatter dateFromString:theTime];
NSString *theString = [timeFormatter stringFromDate:date];
And date comes up nil. I ran into this earlier when I tried this route, and it's not working. Very frustrating.