Last active
November 2, 2017 11:11
-
-
Save Tulakshana/798b3d9cb1dbb9e9002250d5fe568cfd to your computer and use it in GitHub Desktop.
NSString category (Objective C) and String extension (Swift) to format date
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface NSString (DateFormatter) | |
- (NSString *)dateStringFromFormat:(NSString *)fromFormat toFormat:(NSString *)toFormat; | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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