Time

如何正確偽造時間?

  • August 8, 2019

為了解決我正在處理的軟體項目中與特定時區相關的錯誤,我正在嘗試複製系統時鐘上的更改,timedatectl以檢查我的軟體行為。

我試圖通過執行來實現

timedatectl set-timezone America/New_York
timedatectl set-local-rtc 1
timedatectl set-ntp false
timedatectl set-time "2017-03-12 01:58:50" && hwclock -w

當我這樣做並立即執行時timedatectl,我會得到預期的以下時間:

Local time: Sun 2017-03-12 01:58:51 EST
Universal time: Sun 2017-03-12 06:58:51 UTC
RTC time: Sun 2017-03-12 01:58:51
Time zone: America/New_York (EST, -0500)
System clock synchronized: no
systemd-timesyncd.service active: no
RTC in local TZ: yes

但是,在此之後 10 秒,當分鐘更改(變為xx:59)時,本地時間和通用時間會“重新啟動”到目前時間

Local time: Wed 2019-08-07 21:01:41 EDT
Universal time: Thu 2019-08-08 01:01:41 UTC
RTC time: Sun 2017-03-12 01:58:57
Time zone: America/New_York (EDT, -0400)
System clock synchronized: no
systemd-timesyncd.service active: no
RTC in local TZ: yes

我在這裡想念什麼?

我的設置是 Vagrant Ubuntu 18 VM (Linux vagrant 4.15.0-51 / vm box “bento/ubuntu-18.04”)。

這不會解釋您所看到的行為,但它應該回答標題中的問題。

您可以使用環境變數等工具,faketime而不是更改系統的時間:TZ

$ date; faketime -f -15d date; TZ=America/New_York faketime -f -15d date
Thu  8 Aug 10:21:13 CEST 2019
Wed 24 Jul 10:21:13 CEST 2019
Wed 24 Jul 04:21:13 EDT 2019

這將允許您使用自己的時區、日期和時間執行程序,而不會影響系統的其餘部分。

請注意,由於它使用$LD_PRELOADhack 在應用程序中註入程式碼,因此它不適用於靜態連結的執行檔或 setuid/setgid 執行檔。

引用自:https://unix.stackexchange.com/questions/534466