Skip to content

Instantly share code, notes, and snippets.

@s-aska
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s-aska/9525535 to your computer and use it in GitHub Desktop.
Save s-aska/9525535 to your computer and use it in GitHub Desktop.
#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