iOS get Time from Date - iphone

I'm developing an application and I need to parse a Tweet timestamp that actually is a string like this:
"Mon, 17 Oct 2011 10:20:40 +0000"
However what I need it is only the time. So what I'm trying to get it is:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
NSDate *date = [dateFormatter dateFromString:timestamp];
but when I try to print the Date with NSLog the output is (null) and I don't understand why. What I need, if it is possible, is to create a date object only with the time. Indeed later on I need to compare different dates but I care only about the time. It is not important if the date are different because of the day, month or year, the important is that I can compare them with the "timeIntervalSinceDate" to get the difference in seconds.
Any help will be really appreciated.
Thanks
Ale

NSDATE is al full date object, it needs a date en time.
You can use NSDateFormatter to only display the time, but you will need to parse the full string to get the NSDate object.
Here some code you can use:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Mon, 11 Jul 2011 00:00:00 +0200
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"EN"] autorelease]];
[dateFormatter setDateFormat:#"EEE, d MMM yyyy HH:mm:ss ZZZZ"];
NSDate *date = [dateFormatter dateFromString: timestamp];
[dateFormatter release], dateFormatter = nil;
You need to set the local to make sure it read the timestamp in the correct language.
Also alloced the dateFormatter outside any loops and release it after you're done with the loop.

Look at NSDateComponents. You should be able to create a date from components. You'll have to parse the timestamp yourself, though (which should be easy — just split on the colon and grab the number from each component).

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

Required NSDate in PST

I want current date and time in PST. I used this code
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss zzz"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"PST"]];
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
NSLog(#"String:%#",timeStamp);
It returns correct date and time in PST in string form but I want NSDate in PST. So when I change NSString to NSDate like this:
NSDate *currentPST = [dateFormatter dateFromString:timeStamp];
NSLog(#"currentPST Date:%#",currentPST);
It returns date in GMT. I have done R&D but all in vain.Output is:
String:2011-05-18 22:28:54 PDT
currentPST Date:2011-05-19 05:28:54 +0000
Can anyone suggest a solution please.
Thanks in advance
In Cocoa, NSDate is an abstract representation of a date with no time zone information applied.
Whenever you print a NSDate object, it will print the date value corresponds to the default timezone(your device timezone). Your device timezone is GMT thats why you get the value like that. If you look into that deeply, both the time where same, but the timezone varies.

Wrong time from NSDateFormatter

I have a string that I want to parse the time from:
NSString *longdate = #"Mar 27, 2011 8:38:38 PM";
I want to parse this date and output just the time portion w/ hours+minutes+am/pm:
// First, convert our string into an NSDate
NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:#"MMM dd, yyyy HH:mm:ss aaa"];
NSDate *date = [inFormat dateFromString:longdate];
[inFormat release];
// Now convert from date back to a string
NSDateFormatter *outFormat = [[NSDateFormatter alloc] init];
[outFormat setDateFormat:#"HH:mm aaa"];
NSString *final = [outFormat stringFromDate:date];
[outFormat release];
NSLog(#"original: %# | final %#", longdate, final);
The problem is the final time is wrong. I expect the time to be 8:38 PM, but instead I get 12:38 PM.
I just want to get the same hour out that I put it, and not bother w/ any time zones or locales. What am I doing wrong here? Thanks.
Found the problem. Had nothing to do with timezones and everything to do with using the wrong formatting codes for the date formatter.
[inFormat setDateFormat:#"MMM dd, yyyy HH:mm:ss aaa"];
should be:
[inFormat setDateFormat:#"MMM dd, yyyy h:mm:ss aaa"];
Likewise, outFormat's dateformat should be:
[outFormat setDateFormat:#"h:mm aaa"];
After this adjustment everything works fine even w/o any TimeZone adjustments.
As Dave said, check your time zones. You can tell the date formatter to use your current time zone as well:
[outFormat setTimeZone:[NSTimeZone localTimeZone]];
You've got your timezones messed up. IIRC, NSDateFormatter (by default) will parse stuff in the UTC timezone (+000), but dates are NSLogged in your current timezone. Or something like that.
Anyway, check your timezones.

iPhone + Twitter API: Converting time?

Is there an easy way to convert the time stamp you get from twitter into unix time or minutes since now? I could parse through the string and convert everything myself but I'm hoping there is a way to convert that doesn't need that. Here is an example of a created_at element with a time stamp.
Sun Mar 18 06:42:26 +0000 2007
You can use NSDateFormatter with something like this :
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setLocale:usLocale];
[usLocale release];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
// see http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
[dateFormatter setDateFormat: #"EEE MMM dd HH:mm:ss Z yyyy"];
NSDate *date = [dateFormatter dateFromString:[currentDict objectForKey:#"created_at"]];
[dateFormatter release];
NSTimeInterval seconds = [date timeIntervalSince1970];
I have been strugeling with this all day, but this thread helped me to find a solution.
This is how I convert the Twitter "created_at" attribute to a NSDATE;
NSDateFormatter *fromTwitter = [[NSDateFormatter alloc] init];
// here we set the DateFormat - note the quotes around +0000
[fromTwitter setDateFormat:#"EEE MMM dd HH:mm:ss '+0000' yyyy"];
// We need to set the locale to english - since the day- and month-names are in english
[fromTwitter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en-US"]];
NSString *dateString = [item objectForKey:#"created_at"];
NSDate *tweetedDate = [fromTwitter dateFromString:dateString];
I hope someone will find this helpful.
File a feature request with Apple and let them know you want this functionality on the iPhone. NSDateFormatter provides a legacy init method that takes a boolean flag indicating you want it to parse natural language, but it's only available on OS X. Wil Shipley wrote an interesting post a while back about this functionality in the context of heuristics and human factors.
It doesn't seem likely that Apple will provide this functionality as this note would indicate from the NSDateFormatter docs:
iPhone OS Note: iPhone OS supports
only the 10.4+ behavior. 10.0-style
methods and format strings are not
available on iPhone OS.
In other words, I think you'll have to parse it yourself.
Sounds like you need something like: ISO 8601 parser and unparser.

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.