关于 date_format php

about date_format in php

我正在使用 PHP 版本 5.5.15 和 运行 php(在我的本地 windows 机器上)和 Xampp。

我对变量 $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-陪审团的结果:

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())