Skip to content

Instantly share code, notes, and snippets.

@jdriscoll
Created July 30, 2013 13:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdriscoll/6112942 to your computer and use it in GitHub Desktop.
Save jdriscoll/6112942 to your computer and use it in GitHub Desktop.
Common NSDate formats and helpers
//
// NSDate+Formats.h
// Rego
//
// Created by Justin Driscoll on 12/7/12.
// Copyright (c) 2012 Makalu Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSDate (Formats)
+ (NSDate *)fromJSONDate:(NSString *)aJSONDate;
- (NSString *)localizedString;
- (NSString *)localizedStringWithTime;
- (NSString *)toJSONDate;
- (NSString *)stringWithFormat:(NSString *)format;
@end
//
// NSDate+Formats.m
// Rego
//
// Created by Justin Driscoll on 12/7/12.
// Copyright (c) 2012 Makalu Inc. All rights reserved.
//
#import "NSDate+Formats.h"
@implementation NSDate (Formats)
- (NSString *)localizedString
{
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
}
return [dateFormatter stringFromDate:self];
}
- (NSString *)localizedStringWithTime
{
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
}
return [dateFormatter stringFromDate:self];
}
- (NSString *)toJSONDate
{
return [self stringWithFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
}
+ (NSDate *)fromJSONDate:(NSString *)aJSONDate
{
static NSDateFormatter *formatter = nil;
if (formatter == nil) {
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
}
return [formatter dateFromString:aJSONDate];
}
- (NSString *)stringWithFormat:(NSString *)format
{
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
}
dateFormatter.dateFormat = format;
return [dateFormatter stringFromDate:self];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment