1

I have date string like:

08.2015

What I want to do is, to convert it into MySQL compatible date format:

date("Y-m-d", strtotime(date_create_from_format('m.Y', "08.2015")));

Doesn't work as expected. What am I doing wrong?

BTW: It's okay if I'll get 2015-06-01 result.

heron
  • 3,611
  • 25
  • 80
  • 148

6 Answers6

2

You don't need strtotime there.

echo DateTime::createFromFormat('m.Y', "08.2015")->format("Y-m-d");

Output: 2015-08-31

Fiddle

And if you always want to get first date of month with only m.Y given, you can do

echo DateTime::createFromFormat('d.m.Y', "01."."08.2015")->format("Y-m-d");

Output: 2015-08-01

Fiddle

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
  • Note that I have kept `"01"` separate from the rest of the string just to indicate that its a new addition. Otherwise even `"01.$mY"` is fine. – Hanky Panky Jul 31 '15 at 05:27
0
<?php

//explode the date
$dateProps = explode('.',"08.2015");

//prepare the format
$date = $dateProps[1].'-'.$dateProps[0].'-01';

//use date functions
$date = date('Y-m-d', strtotime($date));
Sundar
  • 4,580
  • 6
  • 35
  • 61
0

Try this.

$var = '08.2015';
$date = '01-'.str_replace('.', '-', $var);
echo date('Y-m-d', strtotime($date));
Tarun Upadhyay
  • 724
  • 2
  • 7
  • 16
0

I think below SQL useful to you.

SELECT DATE_FORMAT(STR_TO_DATE('06.2015','%m.%Y'),'%Y-%m');

output: 2015-06

Thank you.

Venkatesh Panabaka
  • 2,064
  • 4
  • 19
  • 27
0

First of all, if you want to use strtotime , it should be this : strtotime('01.08.2015'), that is to say , Year month day must be all needed.

gangzi
  • 105
  • 1
  • 13
0

You can try below sql-

SELECT DATE_FORMAT(STR_TO_DATE('08.2015','%m.%Y'),'%Y-%m-01')
Zafar Malik
  • 6,734
  • 2
  • 19
  • 30