skip to Main Content

I’m trying to save some records in SQL Server using PHP and Laravel and CSV files, in csv files I have a date with format ‘D. d M. Y, g:i:s A’, like ‘lun. 08 ene. 2024, 1:54:02 p. m.’ and I need to convert it into ‘Y-m-d H:i:s’, but it just return this ‘1970-01-01 00:00:00’ when I use just

i’d tried using date and strtotime like this:

<?php
$newDate = date('Y-m-d H:i:s',strtotime('mon. 08 jan. 2024, 1:54:02 p. m.'));

echo $newDate;
?>

2

Answers


  1. Try first replacing Spanish day and month names with their English counterparts using str_replace. Then, DateTime::createFromFormat should be used to parse this adjusted string into a DateTime object according to the specified format. And then, the format method of the DateTime object is used to convert the date into the desired 'Y-m-d H:i:s' format. Hope this helps

    $dateStr = 'lun. 08 ene. 2024, 1:54:02 p. m.';
    $dateStr = str_replace(['ene.', 'lun.'], ['Jan.', 'Mon.'], $dateStr); // Replace Spanish abbreviations with English
    
    $dateObj = DateTime::createFromFormat('D. d M. Y, g:i:s a', $dateStr);
    $newDate = $dateObj->format('Y-m-d H:i:s');
    
    echo $newDate;
    
    Login or Signup to reply.
  2. Custom method for date conversion:

        use CarbonCarbon;
        public function getConvertDate($date)
        {
    
            $monthTranslations = [
                'ene' => 'jan',
                'feb' => 'feb',
                'mar' => 'mar',
                'abr' => 'apr',
                'may' => 'may',
                'jun' => 'jun',
                'jul' => 'jul',
                'ago' => 'aug',
                'sep' => 'sep',
                'oct' => 'oct',
                'nov' => 'nov',
                'dic' => 'dec',
            ];
    
            $translatedDate = strtr($date, array_merge(['lun' => 'Mon', 'mar' => 'Tue', 'mié' => 'Wed', 'jue' => 'Thu', 'vie' => 'Fri', 'sáb' => 'Sat', 'dom' => 'Sun'], $monthTranslations));
    
            $meridianTranslations = [
                'a. m.' => 'am',
                'p. m.' => 'pm',
            ];
    
            $translatedDate = strtr($translatedDate, $meridianTranslations);
    
            return Carbon::createFromFormat('D. d M. Y, g:i:s a', $translatedDate)->format('Y-m-d H:i:s');
        }
    

    Usage:

        echo getConvertDate('lun. 08 ene. 2024, 1:54:02 p. m.');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search