Get the year from specified date php - php

I have a date in this format 2068-06-15. I want to get the year from the date, using php functions. Could someone please suggest how this could be done.

$date = DateTime::createFromFormat("Y-m-d", "2068-06-15");
echo $date->format("Y");
The DateTime class does not use an unix timestamp internally, so it han handle dates before 1970 or after 2038.

You can use the strtotime and date functions like this:
echo date('Y', strtotime('2068-06-15'));
Note however that PHP can handle year upto 2038
You can test it out here
If your date is always in that format, you can also get the year like this:
$parts = explode('-', '2068-06-15');
echo $parts[0];

I would use this:
$parts = explode('-', '2068-06-15');
echo $parts[0];
It appears the date is coming from a source where it is always the same, much quicker this way using explode.

You can try strtotime() and date() functions for output in minimum code and using standard way.
echo date('Y', strtotime('2068-06-15'));
output: 2068
echo date('y', strtotime('2068-06-15'));
output: 68

public function getYear($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("Y");
}
public function getMonth($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("m");
}
public function getDay($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("d");
}

<?php
list($year) = explode("-", "2068-06-15");
echo $year;
?>

You can achieve your goal by using php date() & explode() functions:
$date = date("2068-06-15");
$date_arr = explode("-", $date);
$yr = $date_arr[0];
echo $yr;
That is it. Happy coding :)

Assuming you have the date as a string (sorry it was unclear from your question if that is the case) could split the string on the - characters like so:
$date = "2068-06-15";
$split_date = split("-", $date);
$year = $split_date[0];

$Y_date = split("-","2068-06-15");
$year = $Y_date[0];
You can use explode also

You wrote that format can change from YYYY-mm-dd to dd-mm-YYYY you can try to find year there
$parts = explode("-","2068-06-15");
for ($i = 0; $i < count($parts); $i++)
{
if(strlen($parts[$i]) == 4)
{
$year = $parts[$i];
break;
}
}

Related

Compare a set of integers saved in different variables in php [duplicate]

I have this code:
$curdate = '22-02-2011';
$mydate = '10-10-2011';
if($curdate > $mydate)
{
echo '<span class="status expired">Expired</span>';
}
This would echo expired BUT shouldn't because $mydate is in the future and therefore smaller than the $curdate but PHP is looking at JUST the first two numbers 22 and 10 instead of the whole string. How can I fix this?
Thanks
Try converting them both to timestamps first, and then compare two converted value:
$curdate=strtotime('22-02-2011');
$mydate=strtotime('10-10-2011');
if($curdate > $mydate)
{
echo '<span class="status expired">Expired</span>';
}
This converts them to the number of seconds since January 1, 1970, so your comparison should work.
The problem is that your current variables are strings, and not time variables.
Try this out:
$curdate = strtotime('22-02-2011');
$mydate = strtotime('10-10-2011');
$row_date = strtotime($the_date);
$today = strtotime(date('Y-m-d'));
if($row_date >= $today){
-----
}
$currentDate = date('Y-m-d');
$currentDate = date('Y-m-d', strtotime($currentDate));
$startDate = date('Y-m-d', strtotime("01/09/2019"));
$endDate = date('Y-m-d', strtotime("01/10/2022"));
if (($currentDate >= $startDate) && ($currentDate <= $endDate)) {
echo "Current date is between two dates";
} else {
echo "Current date is not between two dates";
}
Use the PHP date/time classes to convert these string representations into something you can directly compare using getTimestamp() to compare the UNIX times.
If you're sure all your dates are in this format, you can string slice them into YYYY-MM-DD, and a string comparison will function correctly then.
if(strtotime($curdate) > strtotime($mydate))
{
...
}
it's VERY simple
$curdate = '2011-02-22';
$mydate = '2011-10-10';
if($curdate > $mydate)
{
echo '<span class="status expired">Expired</span>';
}

PHP DATE function not working correct and date goes back to 1970

Here is my function
public function test($input, $duration){
$input = date_create($input);
$month = date_format($input,'m-Y');
$monthsArray[] = array(
'month' => $month,
);
for($i=0; $i<$duration; $i++){
$monthsArray[]= array(
'month' => date('m-Y', strtotime("$i months", strtotime($month))),
);
}
var_dump($monthsArray);
}
Here is my input,
test(05-2016,3);
result should be like this,
05-2016 06-2016 07-2016 08-2016
But this function returns
05-2016 01-1970 02-1970 03-1970
Your input date is not in a valid format and also needs to be wrapped in quotes since it ids a string. otherwise you are subtracting 2016 from 5. If you are going to use the m-Y format you need to use DateTime::createFromFormat() to parse that date:
<?php
function test($input, $duration){
$date= DateTime::createFromFormat('m-Y', $input);
$monthsArray = [$input];
for($i=0; $i<$duration; $i++){
$date->modify('+1 month');
$monthsArray[] = $date->format('m-Y');
}
var_dump($monthsArray);
}
test('05-2016',3);
Demo
I removed your usage of strtotime() as it is not needed or recommended for date manipulation.
Also, keep in mind that this code will break at the end of the month due to the fact that not all months have 30 or 31 days.
Your can use like this
<?php
function test($dt,$months){
echo "\n".$dt;
for($i=1;$i<=$months;$i++){
$increseby = "+"."$i";
echo "\n".date('m-Y',strtotime('1-'.$dt." $increseby month"));
}
}
test('05-2016',3);
?>
Check here : https://eval.in/570870

Verifiying 2 date to make sure they're valid dates

I am working with a date which is formatted like so:
25/02/1994 - 15/03/2000
To get each date I am using the explode function to separate each date between dash
$newdate = explode("-",$olddate);
Now my problem is, if it was just one date I could split it up in to 3 parts, the day, month, year and use the checkdate function to validate the month, but because I am using explode I cannot split it up like that (to my knowledge)
What would be the best way to validate the date for legitimacy?
You have a good start, after you exploded your string by -, just simply loop through each date with array_reduce() and reduce it to 1 value.
In the anonymous function you just explode() each date and check with checkdate() if it is a valid date, e.g.
<?php
$str = "25/02/1994 - 15/03/2000";
$dates = explode("-", $str);
if(array_reduce($dates, function($keep, $date){
list($day, $month, $year) = array_map("trim",explode("/", $date));
if(!checkdate($month, $day, $year))
return $keep = FALSE;
return $keep;
}, TRUE)) {
echo "all valid dates";
}
?>
$date = '25/02/1994 - 15/03/2000';
$date_array = explode("-", $date);
$first_date = explode("/", trim($date_array[0]));
$second_date = explode("/", trim($date_array[1]));
if(checkdate($first_date[1],$first_date[0],$first_date[2])){
//do stuff
}
if(checkdate($second_date[1],$second_date[0],$second_date[2])){
//do stuff
}
or, what Daan suggested using the DateTime object.
$date = '25/02/1994 - 15/03/2000';
$date_array = explode("-", $date);
$date1 = DateTime::createFromFormat('j-M-Y', $date_array[0]);
$date2 = DateTime::createFromFormat('j-M-Y', $date_array[1]);
if($date1){
//do stuff
}
if($date2){
//do stuff
}

Change date y-M to Y-m in php

I want to make date from 11-Mar to 2011-03. But I think php is thinking 11-Mar is 2012-Mar-11. How can i do it?
value : 11-Mar
expect : 2011-03
result : 2012-03 [date(strtotime('11-Mar'))]
If you are using PHP >= 5.3.0 Then you can use this...
$date = date_create_from_format('y-M', '11-Mar');
echo date_format($date, 'Y-m');
http://www.php.net/manual/en/datetime.createfromformat.php
You can do this using the DateTime class present in php.
$str = "11-Mar";
$date = DateTime::createFromFormat('y-M', $str);
echo $date->format('Y-m');
http://www.php.net/manual/en/datetime.createfromformat.php
Regards,
$result = date ('Y-m',strtotime('2011-Mar'));
echo $result;
Try
$date= date('Y-m',strtotime('2011 Mar'));
echo $date;
The above is good, this is more exact for what you need to convert FROM:
<?php
$a = "11-Mar";
$date = explode("-", $a);
if ($date[0] <= 99)
$year = '19'.$date[0];
else
$year = '20'.$date[0];
$mon = $date[1];
$date= date('Y-m',strtotime("$year $mon"));
echo $date; // echoes 2011-03
?>

PHP Parse Date String

If I've got a date string:
$date = "08/20/2009";
And I want to separate each part of the date:
$m = "08";
$d = "20";
$y = "2009";
How would I do so?
Is there a special date function I should be using? Or something else?
Thanks!
One way would be to do this:
$time = strtotime($date);
$m = date('m', $time);
$d = date('d', $time);
$y = date('Y', $time);
explode will do the trick for that:
$pieces = explode("/", $date);
$d = $pieces[1];
$m = $pieces[0];
$y = $pieces[2];
Alternatively, you could do it in one line (see comments - thanks Lucky):
list($m, $d, $y) = explode("/", $date);
Check out PHP's date_parse function. Unless you're sure input will always be in a consistent format, AND you validate it first, it is much more stable and flexible, (not to mention easier), to let PHP try to parse the format for you.
e.g.
<?php
//Both inputs should return the same Month-Day-Year
print_r(date_parse("2012-1-12 51:00:00.5"));
print_r(date_parse("1/12/2012"));
?>
If you have a given format you should use a date object.
$date = DateTime::createFromFormat('m/d/Y', '08/20/2009');
$m = $date->format('m');
$d = $date->format('d');
$y = $date->format('Y');
Note you can certainly use only one call to DateTime::format().
$newFormat = $date->format('d-m-Y');
Is it always like that? Or will it be in any sort of file format?
Try strtotime.
Something like:
if(($iTime = strtotime($strDate))!==false)
{
echo date('m', $iTime);
echo date('d', $iTime);
echo date('y', $iTime);
}
how about this:
list($m, $d, $y) = explode("/", $date);
A quick one liner.
For internationalized date parsing, see IntlDateFormatter::parse - http://php.net/manual/en/intldateformatter.parse.php
For example:
$f = new \IntlDateFormatter('en_gb', \IntlDateFormatter::SHORT, \IntlDateFormatter::NONE);
$dt = new \DateTime();
$dt->setTimestamp($f->parse('1/2/2015'));
Dominic's answer is good, but IF the date is ALWAYS in the same format you could use this:
$m = substr($date,0,2);
$d = substr($date,3,2);
$y = substr($date,-4);
and not have to use an array or explode
Bill H

Categories