Category Archives: PHP

Arguments date in PHP

PHP

	if ( isset( $argv ) && isset($argv[1])) {
		$d = DateTime::createFromFormat("Y-m-d", $argv[1]);
		$date_errors = DateTime::getLastErrors();
		
		if ($date_errors['warning_count'] + $date_errors['error_count'] > 0) {
			die();
		}else{
			$obs_date = $argv[1];
		}
	}else{
		$obs_date = date('Y-m-d');
	}

CMD
php index.php 2019-09-10

strtotime (PHP)

<?php
$date_now = date('Y-m-d', strtotime('+1 years'));
$date_now = date('Y-m-d', strtotime("-1 day", strtotime($date_now)));
echo $date_now;
?>

將英文文本日期時間解析為Unix 時間戳:

<?php
    echo(strtotime("now")); //現在時間
    echo(strtotime("3 October 2005")); //2015-10-03
    echo(strtotime("+5 hours")); //現在時間+5小時
    echo(strtotime("+1 week")); //現在時間+1星期
    echo(strtotime("+1 week 3 days 7 hours 5 seconds")); //現在時間 +1星期3天7小時5秒
    echo(strtotime("next Monday")); //下個星期的星期一
    echo(strtotime("last Sunday")); //上個星期的星期天
    //輸出
    //1530144600
    //1473004800
    //1530162600
    //1530749400
    //1531033805
    //1530460800
    //1529769600
?>

日期時間相減
strtotime()轉換成為Unix時間戳,可直接使用兩個時間戳相減計算時間差。

<?php
    echo $time1="2015-11-18 23:00:00";
    echo $time2="2015-11-22 05:00:00";

    echo (strtotime($time1) - strtotime($time2)); //計算相差之秒數
    echo (strtotime($time1) - strtotime($time2))/ (60); //計算相差之分鐘數
    echo (strtotime($time1) - strtotime($time2))/ (60*60); //計算相差之小時數
    echo (strtotime($time1) - strtotime($time2))/ (60*60*24); //計算相差之天數
?>

//計算相差之分鐘數

<?php
$to_time = strtotime("2017-09-12 00:00:00");
$from_time = strtotime("2017-09-12 02:00:00");
echo round(abs($to_time - $from_time) / 60,2). " minute";
?>

strtotime()轉換為日期格式date()

<?php
    //目前時間 加 1小時
    echo date('Y-m-d H:i:s', strtotime('+1 hours'));
    //2017-01-19 13:17:07
?>

Post data to api return json result

<?php 
	$url = http://127.0.0.1/api.php;

	$token = "398cfd96a89a5f45fac326b6778f5da4";
	$agent = $_SERVER['HTTP_USER_AGENT'];

	// POST ITEM
	$query = array(
		"access_token" => $token, 
		"memberID" => "00000001",
	);

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch,CURLOPT_USERAGENT, $agent);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, count($query));
	curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
	$result = curl_exec($ch);
	curl_close($ch);
	$result = json_decode($result, true);

	echo "<pre>";
	print_r($result);
	echo "</pre>";
?>