簡體   English   中英

如何將本地日期時間輸入轉換為 unix 時間戳?

[英]How Do I convert datetime-local input to unix timestamp?

我正在使用類型為datetime-local的輸入。 我需要將其轉換為 unix 時間戳。

這是提交的原始值的格式示例2018-06-12T19:30

我需要將上述格式的日期轉換為這種格式1608954764 ,即當前的 unix 時間戳。

strtotime() 將在給定的時間內返回 Unix 紀元。

<?php
strtotime("2018-06-12T19:30");
?>

您可以使用 date_create_from_format。

date_create_from_format 的優點是避免系統檢測到錯誤的月份和日期(例如 2011-3-10 在不同國家可能表示 3 月 10 日或 10 月 3 日,但 date_create_from_format 是安全的,它會根據您設置的規則進行轉換)

如下:

<?php
$date = date_create_from_format('Y-m-j H:i', str_replace('T',' ', '2018-06-12T19:30'));

echo $date->getTimestamp();
?>

strtotime()是最簡單的選擇,但您確實應該盡可能考慮使用DateTime class。

要使用DateTime獲取 UNIX 時間戳,只需使用format('U')

// returns UNIX timestamp as string
$ts = (new DateTime("2018-06-12T19:30"))->format('U');

這也有一個快捷方式,稱為getTimestamp()

// returns UNIX timestamp as int
$ts = (new DateTime("2018-06-12T19:30"))->getTimestamp();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM