Perl Unix 時間戳程式碼片段
Perl 範例,用於用 time() 取得當前 Unix 時間戳、用 POSIX::strftime() 格式化日期,以及用 Time::Local 將日曆日期轉換回紀元秒。
Current Unix timestamp (seconds)
my $ts = time();Current Unix timestamp (milliseconds)
use Time::HiRes qw(time);
my $ms = int(time() * 1000);Format timestamp as UTC string
use POSIX qw(strftime);
my $str = strftime("%Y-%m-%d %H:%M:%S", gmtime(1700000000));
# "2023-11-15 06:13:20"Format timestamp as local time string
use POSIX qw(strftime);
my $str = strftime("%Y-%m-%d %H:%M:%S", localtime(1700000000));Timestamp from date components (UTC)
use Time::Local qw(timegm);
# timegm(sec, min, hour, mday, mon, year)
# mon is 0-indexed: 10 = November
my $ts = timegm(20, 13, 6, 15, 10, 2023);Timestamp from date components (local)
use Time::Local qw(timelocal);
my $ts = timelocal(20, 13, 6, 15, 10, 2023);Parse ISO date string to timestamp
use Time::Piece;
my $t = Time::Piece->strptime("2023-11-15T06:13:20Z", "%Y-%m-%dT%H:%M:%SZ");
my $ts = $t->epoch;Perl 時間戳記基礎
Perl 內建的 time() 函式以自紀元以來的整數秒數返回目前 Unix 時間戳記。內建的 localtime() 和 gmtime() 把時間戳記轉換為一組日曆值(秒、分、時、日、月、年、星期、年內第幾天、DST 旗標)。gmtime/localtime 的月份從零開始(0 = 一月),年份是自 1900 年以來的年數。
格式化與解析
POSIX 模組隨所有標準 Perl 安裝提供,並提供 strftime(),它用與 C 相同的格式代碼格式化時間戳記。對於次秒精度,Time::HiRes(自 Perl 5.8 起也在核心中)覆寫 time() 和 sleep() 以接受浮點值。Time::Piece(自 Perl 5.10 起在核心中)透過 strptime() 增加了物件導向的解析。
Perl 生產注意事項
Perl 的 time() 返回原生整數,因此在 64 位 Perl 建置上不受 2038 年溢位影響。在 32 位 Perl 建置上,time_t 仍是 32 位;檢查 Config 模組中的 $Config{ivsize}。從日曆分量建構 UTC 時間戳記時,使用 Time::Local 的 timegm(),而非把引數解釋為本地時間的 timelocal()。
- Time::HiRes、POSIX 和 Time::Local 都是核心模組,無需安裝
- timegm() 和 timelocal() 的月份引數從零開始:十一月傳 10
- 年份引數是自 1900 年以來的年數:2023 年傳 123
- 解析任意日期字串時,使用 Time::Piece->strptime,而非手動用正則切分
FAQ
- 為什麼 localtime() 回傳列表而不是字串?
- 在列表上下文中,localtime($ts) 回傳 (sec, min, hour, mday, mon, year, wday, yday, isdst)。在純量上下文中,它回傳 ctime 風格的字串。要從該列表產生自訂格式的字串,請使用 POSIX::strftime。
- 在 Perl 中如何取得亞秒時間戳記?
- 使用 Time::HiRes:'use Time::HiRes qw(time); my $ms = int(time() * 1000);'。該模組是 Perl 核心模組,因此無需從 CPAN 安裝。