I tried to calculate date in php based on this formula:
<?PHP
$lunarMonth = 29.530589;
function getFib($n)
{
return round(pow((sqrt(5)+1)/2, $n) / sqrt(5));
}
$fibbonaciNumber = getFib(2);
$addToDate = sqrt($fibbonaciNumber*$lunarMonth);
$date = '2017-01-01';
$timeStamp = strtotime($date);
$calucatedDate = $timeStamp+$addToDate;
echo 'Date: '.date('Y-m-d', $calucatedDate).'<br>';
?>
But it dosen't work, i cant calculate new date by using timeStamp function. What should i try?
Sample output is:
addToDate: 24.902657870195
timeStemp: 1483311600
CalculateDate: 1483311624.9027
Date: 2017-01-02
This show always the same date, no matter what CalculateDate date is.
I current using excel to calculate this:
=DATE(YEAR(A4)+0#MONTH(A4)+0#DAY(A4)+(29,530589*(SQRT(1)))),
for example input: 2009-02-18, should output: 2009-03-18, for fibonacci number 1
I need to move base date based on calucation $fibbonaciNumber*$lunarMonth
Thanks
I had this bug yesterday (August 31st) where the following printed out...
$timezone = new DateTimeZone('Europe/Helsinki');
$calendar_month_name = DateTime::createFromFormat('m', 9, $timezone)->format('F');
echo $calendar_month_name; // returns October
echo date('M'); // returns August
However, when the date changed to the 1st September, $calendar_month_name corrected itself.
Anyone know why this was? Thanks.
Edit I've turned my calendar back to be on the 31 Aug again, which is why echo date('M'); returns August.
Edit 2 Here is an example using date()
date_default_timezone_set('Europe/Helsinki');
echo date('F', mktime(0,0,0,9)); // returns October
In one line you are asking the name of the month 9 which is September.
On the last line you are asking the short name of the current month.
I think that this is what you intend, isn't?
$calendar_month_name = DateTime::createFromFormat('m', date('m'),$timezone)->format('F');
Cheers!
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;
I need to create functions in PHP that let me step up/down given datetime units. Specifically, I need to be able to move to the next/previous month from the current one.
I thought I could do this using DateTime::add/sub(P1M). However, when trying to get the previous month, it messes up if the date value = 31- looks like it's actually trying to count back 30 days instead of decrementing the month value!:
$prevMonth = new DateTime('2010-12-31');
Try to decrement the month:
$prevMonth->sub(new DateInterval('P1M')); // = '2010-12-01'
$prevMonth->add(DateInterval::createFromDateString('-1 month')); // = '2010-12-01'
$prevMonth->sub(DateInterval::createFromDateString('+1 month')); // = '2010-12-01'
$prevMonth->add(DateInterval::createFromDateString('previous month')); // = '2010-12-01'
This certainly seems like the wrong behavior. Anyone have any insight?
Thanks-
NOTE: PHP version 5.3.3
(Credit actually belongs to Alex for pointing this out in the comments)
The problem is not a PHP one but a GNU one, as outlined here:
Relative items in date strings
The key here is differentiating between the concept of 'this date last month', which, because months are 'fuzzy units' with different numbers of dates, is impossible to define for a date like Dec 31 (because Nov 31 doesn't exist), and the concept of 'last month, irrespective of date'.
If all we're interested in is the previous month, the only way to gaurantee a proper DateInterval calculation is to reset the date value to the 1st, or some other number that every month will have.
What really strikes me is how undocumented this issue is, in PHP and elsewhere- considering how much date-dependent software it's probably affecting.
Here's a safe way to handle it:
/*
Handles month/year increment calculations in a safe way,
avoiding the pitfall of 'fuzzy' month units.
Returns a DateTime object with incremented month/year values, and a date value == 1.
*/
function incrementDate($startDate, $monthIncrement = 0, $yearIncrement = 0) {
$startingTimeStamp = $startDate->getTimestamp();
// Get the month value of the given date:
$monthString = date('Y-m', $startingTimeStamp);
// Create a date string corresponding to the 1st of the give month,
// making it safe for monthly/yearly calculations:
$safeDateString = "first day of $monthString";
// Increment date by given month/year increments:
$incrementedDateString = "$safeDateString $monthIncrement month $yearIncrement year";
$newTimeStamp = strtotime($incrementedDateString);
$newDate = DateTime::createFromFormat('U', $newTimeStamp);
return $newDate;
}
Easiest way to achieve this in my opinion is using mktime.
Like this:
$date = mktime(0,0,0,date('m')-1,date('d'),date('Y'));
echo date('d-m-Y', $date);
Greetz Michael
p.s mktime documentation can be found here: http://nl2.php.net/mktime
You could go old school on it and just use the date and strtotime functions.
$date = '2010-12-31';
$monthOnly = date('Y-m', strtotime($date));
$previousMonth = date('Y-m-d', strtotime($monthOnly . ' -1 month'));
(This maybe should be a comment but it's to long for one)
Here is how it works on windows 7 Apache 2.2.15 with PHP 5.3.3:
<?php $dt = new DateTime('2010-12-31');
$dt->sub(new DateInterval('P1M'));
print $dt->format('Y-m-d').'<br>';
$dt->add(DateInterval::createFromDateString('-1 month'));
print $dt->format('Y-m-d').'<br>';
$dt->sub(DateInterval::createFromDateString('+1 month'));
print $dt->format('Y-m-d').'<br>';
$dt->add(DateInterval::createFromDateString('previous month'));
print $dt->format('Y-m-d').'<br>'; ?>
2010-12-01
2010-11-01
2010-10-01
2010-09-01
So this does seem to confirm it's related to the GNU above.
Note: IMO the code below works as expected.
$dt->sub(new DateInterval('P1M'));
Current month: 12
Last month: 11
Number of Days in 12th month: 31
Number of Days in 11th month: 30
Dec 31st - 31 days = Nov 31st
Nov 31st = Nov 1 + 31 Days = 1st of Dec (30+1)
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');