1

I have a String on the form: "dd/mm-yyyy", where dd is day of the month with two digits, mm is the month represented with two digits, and yyyy is the year with four digits.

I need to store this in my database. Ive tried

$dato = date('d/m-Y' ,strtotime($_POST['dag'] )

But that clearly doesnt work. In my database the date displays as yyyy-mm-dd. How do I properly convert the String to the correct format?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Gard
  • 79
  • 10
  • 2
    On the database it must be formatted as a MYSQL date i.e. `YYYY-MM-DD` – RiggsFolly Jan 10 '17 at 14:32
  • 3
    out of curiosity: what kind of weird format is that even, where you mix `/` and `-`? never seen that one before. – Franz Gleichmann Jan 10 '17 at 14:35
  • @FranzGleichmann ... no format on Earth apparently: https://en.wikipedia.org/wiki/Date_format_by_country ... maybe they're from outer space? – CD001 Jan 10 '17 at 14:37
  • @FranzGleichmann Its more common in written Norwegian, but I guess our official format is dd-mm-yyyy. I just wondered if it was possible. =) – Gard Jan 10 '17 at 14:51

3 Answers3

5

strtotime not accept your time string format, so it return false. You can use DateTime::createFromFormat or date_create_from_format, manual here.

DateTime::createFromFormat('d/m-Y', $_POST['dag']);

check the live demo

<?php

var_dump(DateTime::createFromFormat('d/m-Y', '11/01-2017'));

putput:

object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2017-01-11 14:34:53.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}
LF00
  • 27,015
  • 29
  • 156
  • 295
  • 2
    ... or `DateTime::createFromFormat('d/m-Y', $_POST['dag'])->format('Y-m-d');` to get it into the format used by the database. – CD001 Jan 10 '17 at 14:45
0

Try to replace the / with a - like so:

$date = "02/04-2016";
$dateNew = str_replace("/","-",$date);
WasteD
  • 758
  • 4
  • 24
0

You can use DateTime::createFromFormat:

$time = '12/3-1987';
$data = DateTime::createFromFormat('d/m-Y', $time);
echo $data->format('Y-m-d'); //1987-03-12

sandbox

Ivan
  • 2,463
  • 1
  • 20
  • 28