42

I'm certainly trying to achieve something weird here, but I want to fake the date locally for a shell session on GNU/Linux. I need to black-box test how a program behaves at different dates, and modifying the system-wide date can have unwanted side effects (cron jobs, messed up logs, etc).

Any ideas ?

nicoulaj
  • 1,155
  • 2
  • 10
  • 12

4 Answers4

40

You can just use executable faketime (from ubuntu repositories sudo apt-get install faketime) by:

faketime -f "-15d" date

Or even fake time in whole shell by

faketime -f "-15d" bash -l
abonec
  • 515
  • 5
  • 3
  • 1
    Kyle Brant posted pretty much this answer [back in 2010](http://serverfault.com/a/138371/58408). Please [edit] your answer to expand on it in some way that makes it substantially different from the existing answers. – user Jan 09 '15 at 13:06
  • 6
    My solution is much easier than using library preload as Kyle Brant answered because location of libfaketime .so file is very specific and depends on linux distribution and package managers. – abonec Jan 09 '15 at 13:40
  • 4
    @MichaelKjörling This answer is not at all the same as Kyle Brant's. –  Feb 08 '17 at 17:40
  • 1
    @MichaelKjörling This answer is significantly easier than Kyle Brant's. – Ken Sharp Aug 10 '17 at 22:39
  • I support this answer :-) – Kyle Brandt Oct 24 '20 at 14:17
30

Haven't tried this one out yet. But if this is current is looks like someone already wrote the library you can preload with libfaketime.

The basic usage is:

user@host> LD_PRELOAD=/usr/local/lib/libfaketime.so.1 FAKETIME="-15d" date
Mon Nov  8 12:01:12 CEST 2007

You can use ltrace to make sure all the time functions your application uses are covered.

Kyle Brandt
  • 82,107
  • 71
  • 302
  • 444
7

You can set the TZ variable to an oddball value.

$ date
Tue May  4 06:24:43 CDT 2010
$ date -u
Tue May  4 11:24:47 UTC 2010
$ export TZ='CDT-3:12'
$ date
Tue May  4 14:36:53 CDT 2010
$ export TZ='CDT+5:37'
$ date
Tue May  4 05:48:00 CDT 2010
Dennis Williamson
  • 60,515
  • 14
  • 113
  • 148
  • 1
    Clever trick, but it only modifies the timezone, so this way you are limited to [-12 hours,+11 hours] range. – nicoulaj May 04 '10 at 14:04
  • 3
    @nicoulaj `date Thu Aug 9 12:12:50 CDT 2018`, ` TZ='UTC+120:00' date Sat Aug 4 09:00:47 UTC 2018`, `TZ='UTC-120:00' date Tue Aug 14 09:01:41 UTC 2018`. Roughly +- one week. – phil pirozhkov Aug 09 '18 at 09:01
3

You might be able to preload a library that has an alternative time() implementation.

Douglas Leeder
  • 2,725
  • 18
  • 15
  • 1
    Depending on how the program(s) access current time, you might have to preload alternative implementations of gettimeofday, clock_gettime, and/or possibly others as well, but yes, I've used this approach with success before. – Kjetil Joergensen May 04 '10 at 11:37
  • It's a Java program, and it seems to work well with libfaketime. – nicoulaj May 04 '10 at 14:29