17

In my mysql database I have dates like this: 2011-01-06 09:39:114525

and I need to extraxt separately years, months, days, hours, minutes, seconds from it.

So I need to extract from above example:

2011
01
06
09
39
11

How can I do it ?

6 Answers 6

46

In MySQL, just do MONTH(date), YEAR(date), etc. In PHP, you can do date('g', strtotime($datefromsql)) to get, for example, the 12-hour format hour from the date.

So in your above example, you could either do

SELECT YEAR(date), 
       MONTH(date), 
       DAYOFMONTH(date), 
       HOUR(date), 
       MINUTE(date), 
       SECOND(date)

or in PHP,

$time = strtotime($datefromsql);
echo date('Y', $time);
echo date('m', $time);
echo date('d', $time);
echo date('h', $time);
echo date('i', $time);
echo date('s', $time);
8

Check this link http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

ADDDATE()   Add time values (intervals) to a date value

ADDTIME()   Add time

CONVERT_TZ()    Convert from one timezone to another

CURDATE()   Return the current date

CURRENT_DATE(), CURRENT_DATE    Synonyms for CURDATE()

CURRENT_TIME(), CURRENT_TIME    Synonyms for CURTIME()

CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP  Synonyms for NOW()

CURTIME()   Return the current time

DATE_ADD()  Add time values (intervals) to a date value

DATE_FORMAT()   Format date as specified

DATE_SUB()  Subtract a time value (interval) from a date

DATE()  Extract the date part of a date or datetime expression

DATEDIFF()  Subtract two dates

DAY()   Synonym for DAYOFMONTH()

DAYNAME()   Return the name of the weekday

DAYOFMONTH()    Return the day of the month (0-31)

DAYOFWEEK()     Return the weekday index of the argument

DAYOFYEAR()     Return the day of the year (1-366)

EXTRACT()   Extract part of a date

FROM_DAYS()     Convert a day number to a date

FROM_UNIXTIME()     Format UNIX timestamp as a date

GET_FORMAT()    Return a date format string

HOUR()  Extract the hour

LAST_DAY    Return the last day of the month for the argument

LOCALTIME(), LOCALTIME  Synonym for NOW()

LOCALTIMESTAMP, LOCALTIMESTAMP()    Synonym for NOW()

MAKEDATE()  Create a date from the year and day of year

MAKETIME    MAKETIME()

MICROSECOND()   Return the microseconds from argument

MINUTE()    Return the minute from the argument

MONTH()     Return the month from the date passed

MONTHNAME()     Return the name of the month

NOW()   Return the current date and time

PERIOD_ADD()    Add a period to a year-month

PERIOD_DIFF()   Return the number of months between periods

QUARTER()   Return the quarter from a date argument

SEC_TO_TIME()   Converts seconds to 'HH:MM:SS' format

SECOND()    Return the second (0-59)

STR_TO_DATE()   Convert a string to a date

SUBDATE()   A synonym for DATE_SUB() when invoked with three arguments

SUBTIME()   Subtract times

SYSDATE()   Return the time at which the function executes

TIME_FORMAT()   Format as time

TIME_TO_SEC()   Return the argument converted to seconds

TIME()  Extract the time portion of the expression passed

TIMEDIFF()  Subtract time

TIMESTAMP()     With a single argument, this function returns the date or datetime expression; with two arguments, the sum of the arguments

TIMESTAMPADD()  Add an interval to a datetime expression

TIMESTAMPDIFF()     Subtract an interval from a datetime expression

TO_DAYS()   Return the date argument converted to days

TO_SECONDS()    Return the date or datetime argument converted to seconds since Year 0

UNIX_TIMESTAMP()    Return a UNIX timestamp

UTC_DATE()  Return the current UTC date

UTC_TIME()  Return the current UTC time

UTC_TIMESTAMP()     Return the current UTC date and time

WEEK()  Return the week number

WEEKDAY()   Return the weekday index

WEEKOFYEAR()    Return the calendar week of the date (0-53)

YEAR()  Return the year

YEARWEEK()  Return the year and week
2

Best way to use DateTime class

$my_sql_date = '2011-01-06 09:39:11';
$date_time = new DateTime($my_sql_date);
echo $date_time->format('Y').PHP_EOL;
echo $date_time->format('m').PHP_EOL;
echo $date_time->format('d').PHP_EOL;
echo $date_time->format('h').PHP_EOL;
echo $date_time->format('i').PHP_EOL;
echo $date_time->format('s');
0
$dt = Carbon::now();
$dt->timestamp = strtotime($mysqlVarDatetime); //like '2017-01-31 07:19:11' string cad

it can be result in:

var_dump($dt->year);                                         // int(2017)
var_dump($dt->month);                                        // int(1)
var_dump($dt->day);                                          // int(31)
var_dump($dt->hour);                                         // int(7)
var_dump($dt->minute);                                       // int(19)
var_dump($dt->second);                                       // int(11)

Resource for more information Carbon library: http://carbon.nesbot.com/docs/#api-getters

0

Old thread, but I couldn't resist posting the obvious 'brute-force' solution:

If your SQL date-time string format is always given as in your example, and you don't want to use date-time functions/classes, you can do the following:

$mysql_datetime = "2011-01-06 09:39:114525";
list($date, $time) = explode(' ', $mysql_datetime);
list($year, $month, $day) = explode('-', $date);
list($hr, $min, $sec) = explode(':', $time);
$sec = (int)substr($sec, 0, 2);

The values you want are now available in the following variables: $year, $month, $day, $hr, $min, $sec.

0

I would like to suggest one more cleaner way. And this can be achieved without on any library or framework.

First, you should convert the datetime string to a timestamp (strtotime works on almost every format). Then using getdate as follows :

$dateAsTimestamp = strtotime("2011-01-06 09:39:11.45");
$dateTime = getdate($dateAsTimestamp);

The function returns all components of date and time as an associative array.

Array
(
    [seconds] => 11
    [minutes] => 39
    [hours] => 9
    [mday] => 6
    [wday] => 4
    [mon] => 1
    [year] => 2011
    [yday] => 5
    [weekday] => Thursday
    [month] => January
    [0] => 1294306751
)

Now can be accessed as per your requirement

echo($dateTime['hours']);
echo($dateTime['minutes']);
echo($dateTime['seconds']);

$MONTH = $dateTime['month'];

More on Date/Time Functions - getdate and strtotime

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.