簡體   English   中英

關於php中的date_format

[英]about date_format in php

我正在使用PHP版本5.5.15並使用Xampp運行php(在我的本地Windows機器上)。

我有變量$ time的麻煩。 $ date和$ date2正在運行。

這是代碼:

<?php 
//include_once('connect.php')
function currencyquote() {
    $from = 'EUR';
    $to = 'USD';
    $url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='.$from .$to .'=X';
    $handle = @fopen($url,'r');
    if($handle) {
        $result = fgets($handle, 4096);
        fclose($handle);

    }
    $allData = explode(',',$result);
    $date = $allData[2];  //ex.: "2/18/2015"
    $time = $allData[3];  //ex.: "1:48pm"  -> New York local time
    $close = $allData[1]; // ex.: 1.3151

        echo 'the $result = ' . $result .'<br />'; 
        echo 'the $time = ' .$time. '<br />';

        $date2 = date_create_from_format("h:ia","01:50pm");
        echo 'the $date2 = ' . date_format($date2, "H:i:s") . "<br />";

        $date3 = "01:50pm";
        $date=date_create_from_format("h:ia",$date3);
        echo 'the $date = ' . date_format($date,"H:i:s") . "<br />";

        // this is what i want to use :
        $time1 = date_create_from_format("h:ia", $time);
        echo 'the $time1 = ' . date_format($time1,"H:i:s") . "<br /><br />";   // this line is line 30 of the code

        //with strtotime:
        echo 'using \'date\' = ' . date("h:i:s", strtotime($allData[3])) . "<br />";
        echo 'using \'date()\': '.date('H:i:s', strtotime($time)); 


    }
currencyquote();
?>

以下是php-jury的結果:

the $result = "EURUSD=X",1.1372,"2/19/2015","7:20am"
the $time = "7:20am"
the $date2 = 13:50:00
the $date = 13:50:00

 Warning: date_format() expects parameter 1 to be DateTimeInterface,    boolean given in C:\xampp\htdocs\Nofrafin\php\downloader.php on line 30
 the $time1 =

 using 'date' = 01:00:00
 using 'date()': 01:00:00

您獲得的消息很可能意味着$time1設置為false 原因應該是date_create_from_format()不能匹配日期格式h:is與您提供的變量, $time

進一步向上,你有

$time = $allData[3];  //ex.: "1:48pm"

我嘗試換到$time = '1:48pm'; 這非常有效。 這意味着你沒有從csv獲得你想到的數據。

我試着像你一樣下載同一個文件,然后把它拿回來:

"EURUSD=X",1.1371,"2/19/2015","7:50am"

這就是它不起作用的原因 - $time設置為"7:50am" ,后續換行,而不是7:50am 刪除雙引號(例如$time = trim(str_replace('"', '', $time));你應該沒問題。:)

首先:

對於CSV讀取使用fgetcsv()函數,因此您不必從CSV輸出中過濾引號,也不需要執行explode()。

if($handle) {
    $result = fgetcsv($handle, 4096);
    fclose($handle);

}
$date = $result[2];  //ex.: "2/18/2015"
$time = $result[3];  //ex.: "1:48pm"  -> New York local time
$close = $result[1]; // ex.: 1.3151

...

$time1 = date_create_from_format("G:ia", $time);

其次:

您應該仔細過濾date_create_from_format函數的輸入字符串。

如:

$time = trim(str_replace("\"","", $time)); // you will get something like 7:20am

接着:

$time1 = date_create_from_format("G:ia", $time); // G - for 24-hour format without leading zeroes in your case

但無論如何使用第一個解決方案(fgetcsv())

暫無
暫無

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

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