Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

各主流編程語言獲取與轉換 Unix 時間戳速查表

編輯:Linux 教學

獲取當前 Unix 時間戳(秒級)

語言代碼示例備註
JavaSystem.currentTimeMillis() / 1000毫秒轉秒
JavaScriptMath.floor(Date.now() / 1000)或 Math.round(new Date().getTime()/1000)
C# / .NET(DateTime.UtcNow.Ticks - 621355968000000000) / 10000000Ticks 從 0001-01-01 開始
MySQLSELECT UNIX_TIMESTAMP(NOW())
Perltime
PHPtime()
PostgreSQLSELECT EXTRACT(EPOCH FROM NOW())返回浮點數
Pythonimport time; int(time.time())
RubyTime.now.to_i
SQL ServerSELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())
Linux Shelldate +%s
VBScript/ASPDateDiff("s", "01/01/1970 00:00:00", Now())
命令行perl -e "print time"系統有 Perl 時通用

Unix 時間戳 → 可讀時間

語言代碼示例
Javanew SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(timestamp * 1000L))
JavaScriptnew Date(timestamp * 1000).toLocaleString()
Linuxdate -d @timestamp
MySQLFROM_UNIXTIME(timestamp)
Perllocaltime(timestamp) 返回列表
PHPdate('Y-m-d H:i:s', timestamp)
PostgreSQLTIMESTAMP WITH TIME ZONE 'epoch' + timestamp * INTERVAL '1 second'
Pythontime.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
RubyTime.at(timestamp).strftime('%Y-%m-%d %H:%M:%S')
SQL ServerDATEADD(s, timestamp, '1970-01-01 00:00:00')
VBScriptDateAdd("s", timestamp, "01/01/1970 00:00:00")

可讀時間 → Unix 時間戳

語言代碼示例
Javanew SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2023-01-01 12:00:00").getTime() / 1000
JavaScriptDate.UTC(year, month-1, day, hour, minute, second) / 1000
MySQLUNIX_TIMESTAMP('2023-01-01 12:00:00')
Perluse Time::Local; timelocal(sec, min, hour, day, month-1, year)
PHPmktime(hour, minute, second, month, day, year)
PostgreSQLEXTRACT(EPOCH FROM TIMESTAMP '2023-01-01 12:00:00')
Pythonint(time.mktime(time.strptime('2023-01-01 12:00:00', '%Y-%m-%d %H:%M:%S')))
RubyTime.local(year, month, day, hour, minute, second).to_i
SQL ServerDATEDIFF(s, '1970-01-01 00:00:00', '2023-01-01 12:00:00')
Linuxdate +%s -d "2023-01-01 12:00:00"
VBScriptDateDiff("s", "01/01/1970 00:00:00", "2023-01-01 12:00:00")

注意事項

  • 時區:大多數函數默認使用本地時區,跨時區應用建議統一用 UTC
  • 毫秒/微秒:JS/Java/Python 等常用毫秒,需除以 1000 得到標準 Unix 秒級時間戳
  • 2038 年問題:32 位系統有符號整數上限為 2147483647(2038-01-19),現代系統建議用 64 位時間戳
  • 閏秒:Unix 時間戳不計入閏秒,高精度場景需注意
Copyright © Windows教程網 All Rights Reserved