I have a lot of functionality in my app that is date/time dependent (e.g. "if date is x, show y). I use [NSDate date] to get the current date/time of the user. I can test functionality by manually changing the date/time on my iPhone but I'm wondering if there is a way to programatically overwrite the the current time so I can test in the simulator and more quickly.
Turn on Set Automatically1 in Settings > General > Date & Time. This automatically sets your date and time based on your time zone. If a message appears saying that updated time zone information is available, restart your device and any paired Apple Watch.
By default, the date and time, visible on the Lock Screen, are set automatically based on your location. If you want to change them—for example, when you're traveling—you can adjust them. Go to Settings > General > Date & Time.
Another way of doing it is to provide a custom implementation of +(NSDate *)date. You can swizzle this class method using JRSwizzle. Make a small category for the 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 fixed date do the following:
NSError *error;
[NSDate jr_swizzleClassMethod:@selector(date) withClassMethod:@selector(fixedDate) error:&error];
NSLog(@"Date:%@", [NSDate date]);
The log prints out this:
2011-09-01 11:35:27.844 tests[36597:10403] Date:2011-03-13 07:06:40 +0000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With