Skip to content

Instantly share code, notes, and snippets.

@s-aska s-aska/NSDate+Justaway.m
Last active Aug 29, 2015

Embed
What would you like to do?
#import "NSDate+Justaway.h"
@implementation NSDate (Justaway)
+ (instancetype)dateWithString:(NSString *)string
{
static NSDateFormatter *formatter;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
formatter = NSDateFormatter.new;
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
formatter.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
});
return [formatter dateFromString:string];
}
- (NSString *)absoluteDescription
{
static NSDateFormatter *formatter;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
formatter = [[NSDateFormatter alloc] init];
formatter.locale = [NSLocale currentLocale];
formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
});
return [formatter stringFromDate:self];
}
- (NSString *)relativeDescription
{
NSTimeInterval diff = [[NSDate date] timeIntervalSinceDate:self];
if (diff < 1) {
return @"now";
} else if (diff < 60) {
return [NSString stringWithFormat:@"%ds", (int) diff];
} else if (diff < 3600) {
return [NSString stringWithFormat:@"%dm", (int) (diff / 60)];
} else if (diff < 86400) {
return [NSString stringWithFormat:@"%dh", (int) (diff / 3600)];
} else {
return [NSString stringWithFormat:@"%dd", (int) (diff / 86400)];
}
}
@end
#import <XCTest/XCTest.h>
#import "NSDate+Justaway.h"
@interface NSDate_Justaway : XCTestCase
@end
@implementation NSDate_Justaway
- (void)setUp
{
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
}
- (void)tearDown
{
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
}
- (void)testExample
{
// relativeDescription
XCTAssertEqualObjects([[NSDate date] relativeDescription], @"now");
XCTAssertEqualObjects([[NSDate dateWithTimeIntervalSinceNow:-3] relativeDescription], @"3s");
XCTAssertEqualObjects([[NSDate dateWithTimeIntervalSinceNow:-3*60] relativeDescription], @"3m");
XCTAssertEqualObjects([[NSDate dateWithTimeIntervalSinceNow:-3*60*60] relativeDescription], @"3h");
XCTAssertEqualObjects([[NSDate dateWithTimeIntervalSinceNow:-3*60*60*24] relativeDescription], @"3d");
// absoluteDescription
XCTAssertEqualObjects([[NSDate dateWithString:@"Wed Jun 06 20:07:10 +0900 2012"] absoluteDescription], @"2012/06/06 20:07:10");
XCTAssertEqualObjects([[NSDate dateWithString:@"Wed Jun 06 20:07:10 +0000 2012"] absoluteDescription], @"2012/06/07 05:07:10");
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.