This question already has an answer here:
I want to import csv file into mysql through PHP script.
CSV Format
"Value","Completion date"
"125.38","06/05/2010"
"120.38","10.05.2010"
"452","07/05/2010"
"120","07/05/2010"
"630","07/05/2010"
"200","20.07.2010"
"129.38","15.05.2010"
Here there problem is in date-format. In CSV theer are two types of date dd/mm/yyyy and dd.mm.yyyy format. So I m trying to convert them in to yyyy-mm-dd format using
date("Y-m-d",strtotime($value))
But "strtotime" function count dd/mm/yyyy format as mm/dd/yyyy.
e.g $date =12/11/2014
echo date("Y-m-d",strtotime($date))
//Output 2014-12-11 But (it should be 2014-11-12).
if the separator is a slash (/), then the American m/d/y is assumed so its giving wrong output.I cant change the date format in CSV. What can I do here ?
</div>
I would use DateTime
instead of strtotime
.
if( $date = DateTime::createFromFormat('d.m.Y', $datep) ) {
echo $date->format('Y-m-d') . PHP_EOL;
} else {
$date = DateTime::createFromFormat('d/m/Y', $datep);
echo $date->format('Y-m-d') . PHP_EOL;
}
For example;
<?php
$dates = array("06/05/2010", "10.05.2010");
foreach($dates as $datep) {
echo $datep .' becomes ';
if( $date = DateTime::createFromFormat('d.m.Y', $datep) ) {
echo $date->format('Y-m-d') . PHP_EOL;
} else {
$date = DateTime::createFromFormat('d/m/Y', $datep);
echo $date->format('Y-m-d') . PHP_EOL;
}
}
// 06/05/2010 becomes 2010-05-06
// 10.05.2010 becomes 2010-05-10
You can refer the below code,
$date = str_replace('.', '-', "20.07.2010");
$date = str_replace('/', '-', "20.07.2010");
echo date("d/m/y", strtotime($date));
Format the date string and then pass to strtotime function will work fine.
easiest way of doing by my understanding is
$new_date = implode('-', array_reverse(explode('/', $old_date)));