1

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.

Virender Sood
  • 11
  • 1
  • 3

4 Answers4

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

this is what you are looking for http://php.net/manual/en/class.datetime.php

gabo
  • 1,538
  • 14
  • 15
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