How do I use PHP to get the current year? - php

I want to put a copyright notice in the footer of a web site, but I think it's incredibly tacky for the year to be outdated.
How would I make the year update automatically with PHP 4 or PHP 5?

You can use either date or strftime. In this case I'd say it doesn't matter as a year is a year, no matter what (unless there's a locale that formats the year differently?)
For example:
<?php echo date("Y"); ?>
On a side note, when formatting dates in PHP it matters when you want to format your date in a different locale than your default. If so, you have to use setlocale and strftime. According to the php manual on date:
To format dates in other languages,
you should use the setlocale() and
strftime() functions instead of
date().
From this point of view, I think it would be best to use strftime as much as possible, if you even have a remote possibility of having to localize your application. If that's not an issue, pick the one you like best.

<?php echo date("Y"); ?>

My super lazy version of showing a copyright line, that automatically stays updated:
© <?php
$copyYear = 2008;
$curYear = date('Y');
echo $copyYear . (($copyYear != $curYear) ? '-' . $curYear : '');
?> Me, Inc.
This year (2008), it will say:
© 2008 Me, Inc.
Next year, it will say:
© 2008-2009 Me, Inc.
and forever stay updated with the current year.
Or (PHP 5.3.0+) a compact way to do it using an anonymous function so you don't have variables leaking out and don't repeat code/constants:
©
<?php call_user_func(function($y){$c=date('Y');echo $y.(($y!=$c)?'-'.$c:'');}, 2008); ?>
Me, Inc.

With PHP heading in a more object-oriented direction, I'm surprised nobody here has referenced the built-in DateTime class:
$now = new DateTime();
$year = $now->format("Y");
or one-liner with class member access on instantiation (php>=5.4):
$year = (new DateTime)->format("Y");

http://us2.php.net/date
echo date('Y');

strftime("%Y");
I love strftime. It's a great function for grabbing/recombining chunks of dates/times.
Plus it respects locale settings which the date function doesn't do.

This one gives you the local time:
$year = date('Y'); // 2008
And this one UTC:
$year = gmdate('Y'); // 2008

Here's what I do:
<?php echo date("d-m-Y") ?>
below is a bit of explanation of what it does:
d = day
m = month
Y = year
Y will gives you four digit (e.g. 1990) and y for two digit (e.g. 90)

For 4 digit representation:
<?php echo date('Y'); ?>
2 digit representation:
<?php echo date('y'); ?>
Check the php documentation for more info:
https://secure.php.net/manual/en/function.date.php

echo date('Y') gives you current year, and this will update automatically since date() give us the current date.

print date('Y');
For more information, check date() function documentation: https://secure.php.net/manual/en/function.date.php

use a PHP function which is just called date().
It takes the current date and then you provide a format to it
and the format is just going to be Y. Capital Y is going to be a four digit year.
<?php echo date("Y"); ?>

<?php echo date("Y"); ?>
This code should do

use a PHP date() function.
and the format is just going to be Y. Capital Y is going to be a four digit year.
<?php echo date("Y"); ?>

$dateYear = date('Y');
echo "Current Year: $dateYear";
Current Year: 2022
$dateYear = date('y');
echo $dateYear;
22

If your server supports Short Tags, or you use PHP 5.4, you can use:
<?=date("Y")?>

Just write:
date("Y") // A full numeric representation of a year, 4 digits
// Examples: 1999 or 2003
Or:
date("y"); // A two digit representation of a year Examples: 99 or 03
And 'echo' this value...

BTW... there are a few proper ways how to display site copyright. Some people have tendency to make things redundant i.e.: Copyright © have both the same meaning. The important copyright parts are:
**Symbol, Year, Author/Owner and Rights statement.**
Using PHP + HTML:
<p id='copyright'>© <?php echo date("Y"); ?> Company Name All Rights Reserved</p>
or
<p id='copyright'>© <?php echo "2010-".date("Y"); ?> Company Name All Rights Reserved</p

For up to php 5.4+
<?php
$current= new \DateTime();
$future = new \DateTime('+ 1 years');
echo $current->format('Y');
//For 4 digit ('Y') for 2 digit ('y')
?>
Or you can use it with one line
$year = (new DateTime)->format("Y");
If you wanna increase or decrease the year another method; add modify line like below.
<?PHP
$now = new DateTime;
$now->modify('-1 years'); //or +1 or +5 years
echo $now->format('Y');
//and here again For 4 digit ('Y') for 2 digit ('y')
?>

To get the current year using PHP’s date function, you can pass in the “Y” format character like so:
//Getting the current year using
//PHP's date function.
$year = date("Y");
echo $year;
The example above will print out the full 4-digit representation of the current year.
If you only want to retrieve the 2-digit format, then you can use the lowercase “y” format character:
$year = date("y");
echo $year;
1
2
$year = date("y");
echo $year;
The snippet above will print out 20 instead of 2020, or 19 instead of 2019, etc.

Get full Year used:
<?php
echo $curr_year = date('Y'); // it will display full year ex. 2017
?>
Or get only two digit of year used like this:
<?php
echo $curr_year = date('y'); // it will display short 2 digit year ex. 17
?>

My way to show the copyright, That keeps on updating automatically
<p class="text-muted credit">Copyright ©
<?php
$copyYear = 2017; // Set your website start date
$curYear = date('Y'); // Keeps the second year updated
echo $copyYear . (($copyYear != $curYear) ? '-' . $curYear : '');
?>
</p>
It will output the results as
copyright # 2017 //if $copyYear is 2017
copyright # 2017-201x //if $copyYear is not equal to Current Year.

best shortcode for this section:
<?= date("Y"); ?>

<?php date_default_timezone_set("Asia/Kolkata");?><?=date("Y");?>
You can use this in footer sections to get dynamic copyright year

In Laravel
$date = Carbon::now()->format('Y');
return $date;
In PHP
echo date("Y");

$year = date("Y", strtotime($yourDateVar));

in my case the copyright notice in the footer of a wordpress web site needed updating.
thought simple, but involved a step or more thann anticipated.
Open footer.php in your theme's folder.
Locate copyright text, expected this to be all hard coded but found:
<div id="copyright">
<?php the_field('copyright_disclaimer', 'options'); ?>
</div>
Now we know the year is written somewhere in WordPress admin so locate that to delete the year written text. In WP-Admin, go to Options on the left main admin menu:
Then on next page go to the tab Disclaimers:
and near the top you will find Copyright year:
DELETE the © symbol + year + the empty space following the year, then save your page with Update button at top-right of page.
With text version of year now delete, we can go and add our year that updates automatically with PHP. Go back to chunk of code in STEP 2 found in footer.php and update that to this:
<div id="copyright">
©<?php echo date("Y"); ?> <?php the_field('copyright_disclaimer', 'options'); ?>
</div>
Done! Just need to test to ensure changes have taken effect as expected.
this might not be the same case for many, however we've come across this pattern among quite a number of our client sites and thought it would be best to document here.

create a helper function and call it
getCurrentYear();
function getCurrentYear(){
return now()->year;
}

Print current month with M, day with D and year with Y.
<?php echo date("M D Y"); ?>

For more pricise in second param in date function
strtotime return the timestamp passed by param
// This work when you get time as string
echo date('Y', strtotime("now"));
// Get next years
echo date('Y', strtotime("+1 years"));
//
echo strftime("%Y", strtotime("now"));
With datetime class
echo (new DateTime)->format('Y');

Related

Ranking the current day in PHP automatically

Attempt:
The following code prints the current day of the respective date.
<?php
$current_date = date("D");
echo $current_date;
?>
Output:
The above code gives the following output as:
(As of date: 6/19/2018)
Tue
Required Output:
How can I rank the day automatically as:
Sun1
Mon2
Tue3
Wed4
Thu5
Fri6
Sat7
Required Output Example:
Instead of getting the output as Tue only. What I want the output is Tue3 or similar type.
Suppose today is Tuesday as of (6/19/2018). Then I want the output as:
Tue3
Suggestions are highly appreciated.
http://php.net/manual/en/function.date.php
w = Numeric representation of the day of the week (0 Sun, 6 Sat).
D = A textual representation of a day, three letters.
+1 the w, to give you the right number, then append it.
<?php
$rank = date("w")+1;
echo date("D").$rank;
Result:
Tue3
Hello You can archive by this way
echo date('D').(date('w')+1);
Please refer for more info http://php.net/manual/en/function.date.php

How to write current and future year in link?

I have some links that I want to include the current year in, as well as the following year.
For example:
2016 to 2017
Instead of manually having to maintain the link, I would like to make the current year and future year dynamically print.
Can anyone tell me the best way to accomplish this? The page is PHP, so I wasn't sure if there's a easy way with PHP or jQuery, or something else.
I already tried <?php echo date("Y"); ?> and it didn't work on the front end (it was blank in the spot I was trying to get 2016 to display).
For both year
<?php
$current= new \DateTime();
$future = new \DateTime('+ 1 years');
?>
or you can use it with one line
$current = (new DateTime)->format("Y");
.
<?php echo $current->format('Y')." to ".$future ->format('Y');?>
You probably need something like:
<?php
$year = date("Y");
$nextYear = $year + 1;
echo <<< LOL
$year to $nextYear
LOL;
?>

How to get a specific date in the current year

Suppose the current year is 2014; then I want get the date 2014-06-30, if the current year is 2015 then I want 2015-06-30
I tried date('Y'); but it is just giving current year.
You can just use:
date("Y-06-30")
Demo : https://eval.in/103028
try:
echo date("Y-06-30");
OUTPUT:
2014-06-30
See date documentation:
http://php.net/manual/en/function.date.php
You can concatenate the rest of your required date to your date() function as follow
echo date('Y') . '-06-30';
//output 2014-06-30
Use this :
date("Y-06-30");
Y will be the your year and rest will same.
Where y is A full numeric representation of a year, 4 digits for more Info : Date()
You need to put like below code:
$d = date('Y');
$data = $d."-06-30";
echo $data;

PHP convert 2 digit year to a 4 digit year

I have data coming from the database in a 2 digit year format 13 I am looking to convert this to 2013 I tried the following code below...
$result = '13';
$year = date("Y", strtotime($result));
But it returned 1969
How can I fix this?
$dt = DateTime::createFromFormat('y', '13');
echo $dt->format('Y'); // output: 2013
69 will result in 2069. 70 will result in 1970. If you're ok with such a rule then leave as is, otherwise, prepend your own century data according to your own rule.
One important piece of information you haven't included is: how do you think a 2-digit year should be converted to a 4-digit year?
For example, I'm guessing you believe 01/01/13 is in 2013. What about 01/01/23? Is that 2023? Or 1923? Or even 1623?
Most implementations will choose a 100-year period and assume the 2-digits refer to a year within that period.
Simplest example: year is in range 2000-2099.
// $shortyear is guaranteed to be in range 00-99
$year = 2000 + $shortyear;
What if we want a different range?
$baseyear = 1963; // range is 1963-2062
// this is, of course, years of Doctor Who!
$shortyear = 81;
$year = 100 + $baseyear + ($shortyear - $baseyear) % 100;
Try it out. This uses the modulo function (the bit with %) to calculate the offset from your base year.
$result = '13';
$year = '20'.$result;
if($year > date('Y')) {
$year = $year - 100;
}
//80 will be changed to 1980
//12 -> 2012
Use the DateTime class, especially DateTime::createFromFormat(), for this:
$result = '13';
// parsing the year as year in YY format
$dt = DateTime::createFromFormat('y', $result);
// echo it in YYYY format
echo $dt->format('Y');
The issue is with strtotime. Try the same thing with strtotime("now").
Simply prepend (add to the front) the string "20" manually:
$result = '13';
$year = "20".$result;
echo $year; //returns 2013
This might be dumbest, but a quick fix would be:
$result = '13';
$result = '1/1/20' . $result;
$year = date("Y", strtotime($result)); // Returns 2013
Or you can use something like this:
date_create_from_format('y', $result);
You can create a date object given a format with date_create_from_format()
http://www.php.net/manual/en/datetime.createfromformat.php
$year = date_create_from_format('y', $result);
echo $year->format('Y')
I'm just a newbie hack and I know this code is quite long. I stumbled across your question when I was looking for a solution to my problem. I'm entering data into an HTML form (too lazy to type the 4 digit year) and then writing to a DB and I (for reasons I won't bore you with) want to store the date in a 4 digit year format. Just the reverse of your issue.
The form returns $date (I know I shouldn't use that word but I did) as 01/01/01. I determine the current year ($yn) and compare it. No matter what year entered is if the date is this century it will become 20XX. But if it's less than 100 (this century) like 89 it will come out 1989. And it will continue to work in the future as the year changes. Always good for 100 years. Hope this helps you.
// break $date into two strings
$datebegin = substr($date, 0,6);
$dateend = substr($date, 6,2);
// get last two digits of current year
$yn=date("y");
// determine century
if ($dateend > $yn && $dateend < 100)
{
$year2=19;
}
elseif ($dateend <= $yn)
{
$year2=20;
}
// bring both strings back into one
$date = $datebegin . $year2 . $dateend;
I had similar issues importing excel (CSV) DOB fields, with antiquated n.american style date format with 2 digit year. I needed to write proper yyyy-mm-dd to the db. while not perfect, this is what I did:
//$col contains the old date stamp with 2 digit year such as 2/10/66 or 5/18/00
$yr = \DateTime::createFromFormat('m/d/y', $col)->format('Y');
if ($yr > date('Y')) $yr = $yr - 100;
$md = \DateTime::createFromFormat('m/d/y', $col)->format('m-d');
$col = $yr . "-" . $md;
//$col now contains a new date stamp, 1966-2-10, or 2000-5-18 resp.
If you are certain the year is always 20 something then the first answer works, otherwise, there is really no way to do what is being asked period. You have no idea if the year is past, current or future century.
Granted, there is not enough information in the question to determine if these dates are always <= now, but even then, you would not know if 01 was 1901 or 2001. Its just not possible.
None of us will live past 2099, so you can effectively use this piece of code for 77 years.
This will print 19-10-2022 instead of 19-10-22.
$date1 = date('d-m-20y h:i:s');

PHP Date Calculation to display the next 1st June

I need to be able to calculate a date using PHP that displays the next 1st of June. So, today is 15th April 2013 therefore I need to display 01/06/2013 (UK format). If the date was 5th August 2013 I would need to display 01/06/2014.
Can anyone help?
Thanks,
John
You can achieve this using :
$now = time();
$june = strtotime("1st June");
if ($now > $june)
echo date("d/m/Y", strtotime('+1 year', $june));
else
echo date("d/m/Y", $june);
Hope this helps :)
For this you can achieve by checking the present month
if(date('m')>06)
{
$date= date('d-m-Y',strtotime("next year June 1st"));
}
else{
$date= date('d-m-Y',strtotime("this year June 1st"));
}
echo $date;
Create a new DateTime object for the current year. DateTime is the preferred way to handle dates in PHP.
If it's too early, create a new datetime object for the following year.
Finally, use 'format' to output.
$d = new DateTime(date('Y').'-08-05');
if ($d < new DateTime()) {
$d = new DateTime((date('Y')+1).'-04-15');
}
echo $d->format('d/m/Y');
You can achieve this using this tutorial. You can define time zone and display the date as per your format.
Check this manual. http://php.net/manual/en/function.date.php
clear examples are given here:
<?php
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');
echo $today = date("d/m/y"); // 03/10/01
?>

Categories