-2

I am storing the date in MySQL in the format yyyy-mm-dd. I wish to extract individual elements of the date i.e. day,month and year as separate elements

How should I go about this? I am using php

user2822187
  • 307
  • 2
  • 11
  • 26
  • 2
    `DAY(date)`, `MONTH(date)` and `YEAR(date)` MySQL Functions – George Jan 16 '14 at 12:10
  • if you're doing the sensible thing, and storign it in a [`DATE` or `DATETIME` field](https://dev.mysql.com/doc/refman/5.1/en/datetime.html), then it's simply a case of querying `MONTH(fieldname)`, etc. If you're storing it as a string, then you'll have to `explode()` it into pieces and work on them, but do yourself a favour and use a `DATETIME` field. That's what it's there for. – Spudley Jan 16 '14 at 12:10
  • `sscanf($date, '%d-%d-%d', $Y, $m, $d);` or `list($Y, $m, $d) = explode('-', $date);` – Glavić Jan 16 '14 at 12:14

2 Answers2

0

You could make use of the DateTime class which has the createFromFormat.

Like this..

<?php
$date = DateTime::createFromFormat('Y-m-d', '2009-02-23');
echo $date->format('Y');//2009
echo $date->format('F');//February or use 'M' for Feb
echo $date->format('d');//23
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • Thanks.. Suppose if I want to generalise the above to get all the twelve months should I use a loop or something? Can you please help me with this?? Becasue my date comes from database – user2822187 Jan 16 '14 at 12:26
  • Whatever you are retrieving from the rows to PHP will be intrepreted as a string , so you can directly pass it.. and yeah you can loop it too. – Shankar Narayana Damodaran Jan 16 '14 at 12:37
0

You can do it using explode function in php. explode('-', $date_obj);

cornelv
  • 314
  • 2
  • 13