NSDate Vs NSString vice versa

This is a common issue now a day to work with datetime objects. Sometime it is useful to keep in string and sometime in date date type. Once we start dealing with these two datatypes we often have to convert them to vice versa. For that, one have to make use of NSDateFormatter class. But it is an overkill to end up with repeated lines of code or define a static function and every time call it with the name of class. I came up with a reliable solution that will help you in the same way but won’t let you feel you require some extra effort.

I would like to offer a category for both NSString and NSDate to convert dates vice versa.

NSDate:

.H File

@interface NSDate (Extension)
{
    
}

/*
 This function converts date to string according to the provided format
 If the date is not a valid date or mis-leading format, it will endup with `nil`
 */
-(NSString *)dateToStringWithFormat:(NSString *)format;

@end

.M File

#import "NSDate+Extension.h"

@implementation NSDate (Extension)

-(NSString *)dateToStringWithFormat:(NSString *)format
{
     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
 
    return [formatter stringFromDate:self];
}

@end

NSString:

.H File

#import <Foundation/Foundation.h>

@interface NSString (Extension)
{
    
}

/**
 This function converts date to string according to the provided format
 If the string is not a valid date or mis-leading format, it will endup with `nil`
 */
-(NSDate *)stringToDateWithFormat:(NSString *)format;

@end

.M File

#import "NSString+Extension.h"

@implementation NSString (Extension)

-(NSDate *)stringToDateWithFormat:(NSString *)format
{
     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    return [formatter dateFromString:self];
}

@end

How to use it:

In your view controller, you can simply write like this to test these functions:

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    
    NSDate *currentDate = [NSDate date];
    NSString *stringDate = [currentDate dateToStringWithFormat:@"yyyy/MM/dd"];
    
    NSLog(@"%@", stringDate);
    
    NSDate *convertedDate = [stringDate stringToDateWithFormat:@"yyyy/MM/dd"];
    NSLog(@"%@ %@", convertedDate, currentDate);
}

Note:

Don’t forget to include these category, otherwise you will be getting error messages:

#import “NSDate+Extension.h”
#import “NSString+Extension.h”

Hope it will help you!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s