當(dāng)使用PHP在MySQL中編寫查詢時,它的適用性將基于MySQL本身進(jìn)行檢查。所以使用MySQL提供的默認(rèn)日期和時間格式,即'YYYY-MM-DD'
例子:
ATE: YYYY-MM-DD
Example: 2019-01-28
DATETIME: YYYY-MM-DD HH:MI:SS
Example: 2019-01-28 23:50:30
TIMESTAMP: YYYY-MM-DD HH:MI:SS
Example: 2019-01-28 23:50:30
YEAR: YYYY or YY
用于創(chuàng)建DataBase的MySQL查詢:
CREATE DATABASE Date_time_example;
示例1:用于創(chuàng)建數(shù)據(jù)庫和表的PHP程序
?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// 創(chuàng)建連接
$conn = mysqli_connect( $servername, $username, $password, $dbname );
// 檢查連接
if ( !$conn ) {
die("Connection failed: " . mysqli_connect_error());
}
// 創(chuàng)建表的SQL查詢
$sql = "CREATE TABLE date_test (
id INT AUTO_INCREMENT PRIMARY KEY,
created_at DATETIME
)";
if (mysqli_query($conn, $sql)) {
echo "Table date_test created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
// 關(guān)閉連接
mysqli_close($conn);
輸出:
Table date_test created successfully
示例2:將日期插入表中的PHP程序。
?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// 創(chuàng)建連接
$conn = mysqli_connect( $servername, $username, $password, $dbname );
// 檢查連接
if ( !$conn ) {
die("Connection failed: " . mysqli_connect_error());
}
// 用于向表中插入數(shù)據(jù)的SQL查詢
$sql = "INSERT INTO date_test( created_at )
VALUES( '2019-01-28 12:39:16' );";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "br>" . mysqli_error($conn);
}
// 關(guān)閉連接
mysqli_close($conn);
輸出:
New record created successfully
示例3:此示例用于顯示在2019-01-28上創(chuàng)建的行。使用以下查詢顯示結(jié)果。created_at列不僅包含日期,還包含時間。所以它會顯示錯誤信息。
SELECT * FROM date_test WHERE DATE( created_at ) = '2019-01-28';
?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
//創(chuàng)建連接
$conn = mysqli_connect( $servername, $username, $password, $dbname );
// 檢查連接
if ( !$conn ) {
die("Connection failed: " . mysqli_connect_error());
}
//SQL查詢
$sql = "SELECT * FROM date_test
WHERE DATE(created_at) = '2019-01-28'";
$result = mysqli_query( $conn, $sql );
if ($result) {
echo $result; //打印查詢結(jié)果
}
else {
echo "Error: " . $sql . "br>" . mysqli_error($conn);
}
// 關(guān)閉連接
mysqli_close($conn);
輸出:
id created_at
1 2019-01-28 12:39:16
要從DATETIME值獲取年,季度,月,周,日,小時,分鐘和秒,請使用以下語句中顯示的函數(shù):
HOUR(@dt),MINUTE(@dt),SECOND(@dt) ),DAY(@dt),WEEK(@dt),MONTH(@dt),QUARTER(@dt),YEAR(@dt);
您可能感興趣的文章:- PHP如何通過date() 函數(shù)格式化顯示時間
- PHP格式化顯示時間date()函數(shù)代碼
- js模仿php中strtotime()與date()函數(shù)實(shí)現(xiàn)方法
- PHP date()函數(shù)警告: It is not safe to rely on the system解決方法
- 關(guān)于php程序報date()警告的處理(date_default_timezone_set)
- PHP中time(),date(),mktime()區(qū)別介紹
- PHP函數(shù)之日期時間函數(shù)date()使用詳解
- PHP格式化顯示時間date()函數(shù)案例講解