Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Year/Month/Day from a datetime in php?

Tags:

php

I used date('w', timestamp) and date('w', timestamp) to know the day, date('n', timestamp) for months, etc.

Now I'm using datetime and I'd like to know what are the equivalent functions to get a day, a month, etc from a datetime.

PS: I know I could use UNIX_TIMESTAMP() in a SQL query but I prefer avoiding timestamps using in my code.

like image 277
Anon Avatar asked Aug 30 '11 17:08

Anon


People also ask

How to get year in php from date?

$date = DateTime::createFromFormat("Y-m-d", "2068-06-15"); echo $date->format("Y");

What is Strtotime php?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.


2 Answers

Use DateTime with DateTime::format()

$datetime = new DateTime($dateTimeString); echo $datetime->format('w'); 
like image 196
KingCrunch Avatar answered Oct 05 '22 10:10

KingCrunch


Check out the manual: http://www.php.net/manual/en/datetime.format.php

<?php $date = new DateTime('2000-01-01'); echo $date->format('Y-m-d H:i:s'); ?> 

Will output: 2000-01-01 00:00:00

like image 33
etuardu Avatar answered Oct 05 '22 11:10

etuardu