Skip to content

Instantly share code, notes, and snippets.

@Tulakshana
Last active November 2, 2017 11:11
Show Gist options
  • Save Tulakshana/798b3d9cb1dbb9e9002250d5fe568cfd to your computer and use it in GitHub Desktop.
Save Tulakshana/798b3d9cb1dbb9e9002250d5fe568cfd to your computer and use it in GitHub Desktop.
NSString category (Objective C) and String extension (Swift) to format date
#import <Foundation/Foundation.h>
@interface NSString (DateFormatter)
- (NSString *)dateStringFromFormat:(NSString *)fromFormat toFormat:(NSString *)toFormat;
@end
//http://www.alexcurylo.com/2009/01/28/nsdateformatter-formatting/
#import "NSString+DateFormatter.h"
@implementation NSString (DateFormatter)
- (NSString *)dateStringFromFormat:(NSString *)fromFormat toFormat:(NSString *)toFormat{
NSDateFormatter *fromFormatter = [[NSDateFormatter alloc]init];
[fromFormatter setDateFormat:fromFormat];
NSDate *fromDate = [fromFormatter dateFromString:self];
NSDateFormatter *toFormatter = [[NSDateFormatter alloc]init];
[toFormatter setDateFormat:toFormat];
return [toFormatter stringFromDate:fromDate];
}
@end
extension String{
func dateStringFromFormat (fromFormat:String, toFormat:String) -> String{
let fromFormatter:NSDateFormatter = NSDateFormatter()
fromFormatter.dateFormat = fromFormat
let fromDate:NSDate? = fromFormatter.dateFromString(self)
let toFormatter:NSDateFormatter = NSDateFormatter()
toFormatter.dateFormat = toFormat
if let date = fromDate{
return toFormatter.stringFromDate(date)
}
return ""
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment