Include Framework to get date information Objective-C - objective-c

I am new to objective-C and I am trying to insert NSdate but I don't know which library to include in order to call it. I tried the following but without success. Thanks for your help
#import <Cocoa/Cocoa.h>
#import <Foundation/Foundation.h>
#include <CoreFoundation/CoreFoundation.h>
// Get current datetime
NSDate *currentDateTime = [NSDate date];
// Instantiate a NSDateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// Set the dateFormatter format
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
// Get the date time in NSString
NSString *dateInString = [dateFormatter stringFromDate:currentDateTime];
// Release the dateFormatter
[dateFormatter release];

You have included every necessary header and you added every necessary framework (all you need for NS* classes is Foundation). The problem is that your statements don't have a scope. Wrap them, for example, in the main() function.

Related

Swift 3 getting an optional value from objective-c class?

I have a project that still has a lot of objective-c code, like this one:
+ (NSString *)getDaysFromDateString:(NSString *)dateString
{
// Creating and configuring date formatter instance
NSLocale *ptBRLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"pt_BR"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"];
[dateFormatter setLocale:ptBRLocale];
// Retrieve NSDate instance from stringified date presentation
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
// Retrieve date with increased days count
NSDate *newDate = [dateFromString dateByAddingTimeInterval:-30*24*60*60];
return [dateFormatter stringFromDate:newDate];
}
This was working fine with my Swift 2.2 project (this project has both Swift and Objective-c) and always returned a value. Now, I have migrated my code to Swift 3.0 and for some reason the method above returns an optional value. How can I make the code above return a non-optional value again?

nsformatter dateFromString is nil

Im working on iphone app using xcode,objective c and targeting ios 5 minimum.
All I am trying to do is convert a string to a date. I have read lots on this and it should be a simple straight forward task. I have seen many other questions like this in forum but what is working for people doesnt seem to be working for me.
Here is what I am doing
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *dobText = [dict valueForKey:#"DateOfBirth"];
NSDate *dobDate = [dateFormatter dateFromString:dobText];
the dobText is always in format #"1999-01-01" which matches the date format set in the date formatter but the result when using date from string is always nil.
can anyone explain this to me and let me know how to fix it?
Look at the user preferences on your device. The documentation says:
Note that although setting a format string (setDateFormat:) in
principle specifies an exact format, in practice it may nevertheless
also be overridden by a user’s preferences—see Data Formatting Guide
for more details.
are you sure the date is using a - and not a – in the data you get from the dict. As i can reproduce a nil result when i use a – (alt + -)
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *dobText = #"2009-02-12";
NSDate *dobDate = [dateFormatter dateFromString:dobText];
NSLog(#"%#", dobDate);
Try doing this, will likely fix your problem.
NSString *dobText = [[dict valueForKey:#"DateOfBirth"] stringByReplacingOccurrencesOfString:#"—" withString:#"-"];
I suspect like bigkm say, your dashes may be getting in the way.
I would suggest you try a dummy string in line first. e.g.
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *dobText = #"1999-01-01" // [dict valueForKey:#"DateOfBirth"];
NSDate *dobDate = [dateFormatter dateFromString:dobText];
Now does that work? It should. Now triangulate another way:
Remove the dashes completely from the dob text, so that it has the format 'yyyyMMdd'
Have the date formatter look for this same format
Does that work? It should. And that would prove that the separator characters in your format are the issue and need some further inspection (or cleansing as bigkm suggested).
Side node re threading: NSDateFormatter is fine if you use it on the thread on which it was created. If you don't, you'll know b/c the app will crash.
If your date format is correct, I can suggest to set NSLocale to your NSDateFormatter.
For me this code works on simulator:
NSString *format = [NSString stringWithFormat:#"EEE, dd MMM yyyy HH:mm:ss Z"];
NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:format];
NSDate *date = [df dateFromString:pubDateSttring];
but on the device date is always NIL.
I've found workaround of setting NSLocale:
df.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];

Is there a way to get Xcode's debugger to show dates in local timezone (i.e., not UTC)?

I'm trying to debug code that makes pretty heavy use of dates which has me comparing tons of different NSDate values in the debugger. The debugger is displaying those dates in UTC format--for example:
date1 = (NSDate *) 0x01b11460 #"2012-02-15 18:55:00 +0000"
It would be a lot easier for me if it would show them in my local timezone as that is what the test code I'm debugging seems to be using.
I do have feeling that I'm missing something much more basic here so I'm hoping someone can enlighten me. Thanks in advance.
While a little "hackish" you can create a subclass of NSDate and override just the
-(NSString *)description;
method to return a date formatted however you want.
The debugger isn't doing any special decoding for you, it's just calling the "description" method of the object it wants to display. A handy trick... (Which is why all my objects publish a concise description suitable for viewing in a debugger.)
In the end, what worked best was in fact adding a Category for NSDate that just overrides the description method to return a string that represents the NSDate in my current timezone. I also made it DEBUG only as I really just need this override in place when debugging.
Here's the .h file I used:
#ifdef DEBUG
#interface NSDate (DebugHelper)
-(NSString *)description;
#end
#endif
and the .m file:
#ifdef DEBUG
#import "NSDate+DebugHelper.h"
#implementation NSDate (DebugHelper)
-(NSString *) description
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
return [dateFormatter stringFromDate:self];
}
#end
#endif
Thanks to Jim Hayes and jrturton for the discussion and ideas that led to this answer.
Just did the same thing, however instead of systemTimeZone I used localTimeZone (see the docs as to why it is slightly better). Also I noticed you are alloc'ing the dateFormatter object but never releasing it which is a leak.
Here's my category method:
-(NSString *) description;
{
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]autorelease];
NSLocale *enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"] autorelease];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
NSString *dateString = [dateFormatter stringFromDate:self];
return dateString;
}

How can I Convert a NSString to a valid NSDate (iOS)

I'm passing a string from javascript to Objective-C in the form of "2012-02-17 14:21:30 +0000".
My code is as follows:
NSString *firingDate = [_parameters objectForKey:#"fire"];
NSDate *notificationDate = [NSDate dateWithString:firingDate];
The issue is that I ended up reading the OS X reference instead of the iOS docs (doh!) so this throws a warning as dateWithString isn't present in iOS. In theory I suppose that this shouldn't work at all but it does, albeit with that warning.
What is the Correct way to convert the string to a NSDate?
The correct way is to use NSDateFormatter as a factory to create dates from strings (and vice versa).
Try:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"YYYY-MM-dd HH:mm:ss Z";
NSDate *notificationDate = [formatter dateFromString:firingDate];
Try this:
NSString *firingDate = [_parameters objectForKey:#"fire"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *notificationDate = [dateFormatter dateFromString:firingDate];
Check out the reference for parsing dates from multiple regions.
Don't forget to release your formatter when finished.

Conditional Methods based on Operating System Version

I am sure this is really simple, but I'm not sure even how to search for it, as I have seen example of what I think are called compiler flags?, but in general whats the best method in cocoa of condtionally running a specific method on Operating System Versions that support it. as an example the NSDateFormatter Class has the setDoesRelativeDateFormatting method which only works on 10.6 (on the Mac) and higher.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setLocale:enLocale];
[dateFormatter setDoesRelativeDateFormatting:YES];
Here's how Adium detected that it was running on Snow Leopard or better to do stuff like this (this was in a category on NSApplication):
//Make sure the version number defines exist; when compiling in 10.5, NSAppKitVersionNumber10_5 isn't defined
#ifndef NSAppKitVersionNumber10_5
#define NSAppKitVersionNumber10_5 949
#endif
- (BOOL)isOnSnowLeopardOrBetter
{
return (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5);
}
Then all you have to do is
if ([NSApp isOnSnowLeopardOrBetter]) { ... }
You can find the version numbers for AppKit by command-clicking on NSAppKitVersionNumber to jump to its definition.
For this particular case, it should be easy enough to do the following:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setLocale:enLocale];
if ([dateFormatter respondsToSelector:#selector(setDoesRelativeDateFormatting:)]) {
[dateFormatter setDoesRelativeDateFormatting:YES];
}
See NSObject protocol's -respondsToSelector: for more info.