I want to store a specific date in a variable. If stored like $x="01/01/2016"
it is acting as a string from which I cannot extract a part, like from getdate()
year, month, day of the month, etc.
Asked
Active
Viewed 8,047 times
1

S.L. Barth is on codidact.com
- 8,198
- 71
- 51
- 66

Virender Sood
- 11
- 1
- 3
-
Do you want something like this? http://stackoverflow.com/questions/6238992/converting-string-to-date-and-datetime – CyberEd May 20 '16 at 05:57
-
try `echo date('y-m-d',strtotime(str_replace('/', '-', $x )));` – Maninderpreet Singh May 20 '16 at 05:58
4 Answers
5
Use the DateTime object:
$dateTime = new DateTime('2016/01/01');
To get only parts of the date you can use the format
method:
echo $dateTime->format('Y'); // it will display 2016
If you need to create it from the format you wrote in the question, then you can use the factory method createFromFormat
:
$dateTime = DateTime::createFromFormat('d/m/Y', '01/01/2016');
echo $dateTime->format('Y/m/d');

Mihai Matei
- 24,166
- 5
- 32
- 50
0
This is work for me
$date = '20/May/2015:14:00:01';
$dateInfo = date_parse_from_format('d/M/Y:H:i:s', $date);
$unixTimestamp = mktime(
$dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
$dateInfo['month'], $dateInfo['day'], $dateInfo['year'],
$dateInfo['is_dst']
);

SAUMYA
- 1,508
- 1
- 13
- 20
0
You can use $myDate = new DateTime('01/01/2016');
to declare date. To get year, month and date from the specified date, use echo $myDate->format('d m Y');
Change the format based on your need. To know more about date format refer

Karthikeyani Srijish
- 470
- 3
- 7