2

Goal: I want to save some data from an api to my database, the date looks like this in the api:

"utcDate": "2018-10-28T13:30:00Z"

I tried using datetime in my migrations but I'm getting errors that this is not the right format.

$table->datetime('date');

My error:

PDOException::("SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2018-10-20T11:30:00Z' for column 'date' at row 1")

Any other ways of storing this date as date in my database?

Dax
  • 767
  • 4
  • 11
  • 29
  • or dup of https://stackoverflow.com/questions/19357284/mysql-how-to-convert-date-from-iso-8601-format-and-save-to-mysql-column – user3783243 Oct 28 '18 at 16:11
  • 1
    This is *NOT* a dupe--Laravel/MySQL doesn't require Eloquent models to be converted to Unix timestamps. Eloquent formats the value for the database automatically when provided a DateTime object, so there's no need to convert anything beyond getting the date string into a DateTime object in the first place. – John Ellmore Jan 08 '19 at 16:17

2 Answers2

1

You need to convert it to date form datetime using DateTime before going to insert the value, It is causing error because $table->datetime('date'); doen't work for you to convert it to date format. Also you can use MYSQL DATE() to cast it to date from datetime.

<?php

$datetime = "2018-10-28T13:30:00Z";
$date = new DateTime($datetime);
echo $date->format('Y-m-d');
?>

OR

<?php
$datetime = "2018-10-28T13:30:00Z";
echo date("Y-m-d", strtotime($datetime));
?>
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

I think this query is simple to do it by use DATE() method from MySQL

    INSERT INTO `test`
    (`createdAt`)
    VALUES
    (DATE('2018-01-01 07:00:01'));
giapnh
  • 2,950
  • 24
  • 20