What is the date and time of the iPhone in the test application?

I have a lot of functionality in my application depending on the date and time (for example, "if the date is x, show y"). I use [NSDate date] to get the current date / time of the user. functionality by manually changing the date / time on my iPhone, but I'm wondering if there is a way to programmatically overwrite the current time so that I can test in the simulator and faster.

+5
source share
4 answers

You can create NSDate objects with any date / time you want. Just run your code using the method to get the "current" time, and inside this method return the actual date for production or some date of your choice for testing.

+3
source

Another way to do this is to create a custom implementation of date + (NSDate *). You can use this class method using JRSwizzle . Create a small category for NSDate:

static NSTimeInterval seconds = 1300000000;

@interface NSDate (Fixed)
   + (NSDate *)fixedDate;
@end

@implementation NSDate (Fixed)
+ (NSDate *)fixedDate
{
  return [NSDate dateWithTimeIntervalSince1970:seconds];
}
@end

Then in the code where you want to have a fixed date, do the following:

NSError *error;
[NSDate jr_swizzleClassMethod:@selector(date) withClassMethod:@selector(fixedDate) error:&error];
NSLog(@"Date:%@", [NSDate date]);

The magazine prints this:

2011-09-01 11:35:27.844 tests[36597:10403] Date:2011-03-13 07:06:40 +0000
+5
source

NSDate +[NSDate date]

+ (instancetype)date
{
  return [NSDate dateWithTimeIntervalSince1970:100000]; // Replace with any date you want
}
+2
source

dateByAddingTimeInterval:

Returns a new NSDate that is set to the specified number of seconds relative to the receiver.

- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds

Second Settings The number of seconds to add to the receiver. Use a negative value in seconds so that the returned object indicates the date before the receiver. Return Value A new NSDate that is set in seconds in seconds relative to the receiver. The returned date may have a different presentation from the recipients.

source: documentation: p

0
source

All Articles