Beny Bond Banjarnahor Beny Bond Banjarnahor - 11 months ago 102
PHP Question

output date different with original date

Here's my problem. output date different from the string i cut. I've tried the code below and the day not match with the original date. it should "26" but output "02", give me solution.

CODE :

$line = 'File=D:\Shared\print\2017\september\26\printing\baryun - cetak transferpaper.tif';
$r = "/^File=D:\\\\[a-zA-Z]+\\\\[a-z]+\\\\([0-9]{4})\\\\([a-z]+)\\\\([0-9]{1,2})/";

if (preg_match($r, $line, $match)) {
$date = $match[1]."-".$match[2]."-".$match[3];
echo $date."<br>";
$xtime = strtotime($date);
$tes = date("Y-m-d",$xtime);

echo $tes;
}


OUTPUT :

2017-september-26
2017-09-02


And when i try this code

if (preg_match($r, $line, $match)) {
$date = $match[1]."-".$match[2]."-".$match[3];
echo $date."<br>";
$xtime = date_create($date);
$tes = date_format($xtime,"Y-m-d");

echo $tes;


OUTPUT, the day 01. please help me

2017-september-26
2017-09-01

Answer Source

It's because the date string you are trying to pass is not-correctly formatted.

Do like below:-

$r = "/([0-9]{4})\\\\([a-z]+)\\\\([0-9]{1,2})/"; // curtale your regex
if (preg_match($r, $line, $match)) {
    $date = $match[3]."-".$match[2]."-".$match[1]; //change the pattern
    echo $date."<br>";
    $xtime = strtotime($date);
    $tes = date("Y-m-d",$xtime);

    echo $tes;
}

https://eval.in/872478

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download