Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set iPhone date/time within app for testing purposes?

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.

like image 537
Martin Avatar asked Apr 20 '11 13:04

Martin


People also ask

How do I adjust the Time on my iPhone automatically?

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.

How do I change the Date format on my iPhone?

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.


1 Answers

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
like image 58
Vytis Avatar answered Sep 22 '22 01:09

Vytis