1

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 ?

kreya
  • 1,091
  • 5
  • 24
  • 52
  • @SverriM.Olsen : I checked that But its not related to this case.here I m ibserting into DB.its allow inly yyyy-mm-dd format. IF I used strtotime then for dd/mm/yyyy format its count mm as dd – kreya Nov 13 '14 at 11:14
  • It is identical to this question. Read [this answer](http://stackoverflow.com/questions/2487921/convert-date-format-yyyy-mm-dd-dd-mm-yyyy#answer-11435664). – Sverri M. Olsen Nov 13 '14 at 11:16

3 Answers3

4

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

https://eval.in/220804

ʰᵈˑ
  • 11,279
  • 3
  • 26
  • 49
  • 1
    There is no reason to use a regular expression. `createFromFormat()` returns `false` if the format did not match. You can just try both formats, and use the one that works. – Sverri M. Olsen Nov 13 '14 at 11:23
  • Very true @SverriM.Olsen - made amendments, thanks! – ʰᵈˑ Nov 13 '14 at 11:26
1

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.

Ashique C M
  • 733
  • 4
  • 8
1

easiest way of doing by my understanding is

$new_date = implode('-', array_reverse(explode('/', $old_date)));