Count years from date php

PHP: Calculating past and future dates

The strtotime function in PHP is incredibly powerful but very much underutilised — mainly because some aspects can be a bit confusing and people are more confident ‘doing things the hard way’. The strtotime function doesn’t just convert date strings to timestamp values but also has its own ‘language’ to let you specify just about any date or time you want.

Calculating dates for past and future days

The easiest and most common calculations are based on seconds, minutes, hours and days. Months and years are also valid input but not always useful in calculations as they’re not all of equal length because of the way our calendar works.

Shown below are the results of various strings passed to strtotime and converted to date strings.

Читайте также:  Install php http extension

echo date(‘l jS F (Y-m-d)’, strtotime(‘-3 days’)); 3 days ago Monday 17th July (2023-07-17) -3 days Monday 17th July (2023-07-17) -2 days Tuesday 18th July (2023-07-18) yesterday Wednesday 19th July (2023-07-19) now Thursday 20th July (2023-07-20) today Thursday 20th July (2023-07-20) tomorrow Friday 21st July (2023-07-21) +2 days Saturday 22nd July (2023-07-22) +3 days Sunday 23rd July (2023-07-23)

As always there are often different ways to achieve the same result. In the list above you can see that ‘3 days ago’ is equivalent to ‘-3 days’. Also ‘yesterday’ is the same as ‘-1 days’ or ‘1 day ago’. The ‘s’ on the end of ‘days’, ‘years’ or other measurements can be left off if you want.

The ‘now’ and ‘today’ input values in the list above are superfluous as if we leave off the second paramater of the date function it will default to the current time anyway.

Working with days of the week

Sometimes we work with days of the week and need to know the last/next occurrence of, for example, a Saturday:

-2 weeks Saturday Saturday 8th July (2023-07-08) last Saturday Saturday 15th July (2023-07-15) Saturday Saturday 22nd July (2023-07-22) this Saturday Saturday 22nd July (2023-07-22) first Saturday Saturday 22nd July (2023-07-22) next Saturday Saturday 22nd July (2023-07-22) third Saturday Saturday 5th August (2023-08-05) +2 weeks Saturday Saturday 5th August (2023-08-05)

In the list above we can see that ‘Saturday’, ‘this Saturday’ and ‘first Saturday’ are all equivalent. The ‘this’ and ‘first’ keywords are only used to improve readability.

Now it gets a bit complicated to explain. The following appears on the PHP website:

In PHP 5 up to 5.0.2, «now» and other relative times are wrongly computed from today’s midnight. It differs from other versions where it is correctly computed from current time.

In addition, they’ve introduced ‘second’ as in ‘second Saturday’ and seem to have changed the meaning of ‘next’ to mean the same as ‘first’. Finally, the return value on failure is now FALSE instead of -1. This last change is the most likely to cause problems in legacy applications.

The table below shows how the output has changed:

  • last Saturday
  • this Saturday or first Saturday
  • next Saturday
  • third Saturday
  • fourth Saturday
  • last Saturday
  • this Saturday or first Saturday or next Saturday
  • second Saturday
  • third Saturday
  • fourth Saturday

Using offsets to get the right day

Another problem is when you want to find the previous or next occurence of a certain day of the week. For example, today being a Thursday we can run the following:

  • last Thursday
  • this Thursday or first Thursday
  • next Thursday
  • third Thursday
  • fourth Thursday
  • last Thursday
  • this Thursday
  • first Thursday or next Thursday
  • second Thursday
  • third Thursday

You can see in the table above that, while ‘next Thursday’ returns the same result, the ‘first’, ‘second’, ‘third’, . modifiers have all changed in meaning — thankfully to a more logical state.

You may notice also that this only occurs when you’re calculating from the current day and not in the previous examples (unless today is Saturday). Whenever you do calculations based on days you should test as many possibilities as possible: Does it work today? yesterday? tomorrow? and so on.

Sometimes you want to find the last occurence of a day before today, or before yesterday or before 2 days ago. The following examples show the syntax you can use for this:

-3 days last Saturday Wednesday 12th July (2023-07-12) -2 days last Saturday Thursday 13th July (2023-07-13) yesterday last Saturday Friday 14th July (2023-07-14) tomorrow Saturday Sunday 23rd July (2023-07-23) +2 days Saturday Monday 24th July (2023-07-24) +3 days Saturday Tuesday 25th July (2023-07-25)

Now that you understand the inner workings of strtotime you should be able to drastically reduce the amount of code required to calculate past and future dates.

Checking if a date is in the Past or Future

The strtotime function returns an integer value so it’s a simple matter to see if a date is in the past or in the future.

if(strtotime(dateString) > time()) < # date is in the future >if(strtotime(dateString) < time()) < # date is in the past >if(strtotime(dateString) == time())

time() is equivalent to date('U') and returns the current timestamp to the nearest second.

You might want to replace time() with strtotime('0:00') if you want to compare a date string to the current date rather than the current date and time.

References

Источник

Count years from date php

Эта заметка не столько для меня, сколько для людей, которые хотят посчитать количество лет между какой-то датой и текущим днем при помощи языка PHP. Сам же я уже реализовал это в верхнем левом блоке, который автоматически выводит, сколько лет я уже занимаюсь разработкой в сфере создания сайтов.

За начальную дату я взял дату создания первого собственного домена второго уровня — 01.03.2009. Особо внимательные поймут, о каком домене идет речь =)

Задача понятна: нужно было просто рассчитать разницу между 01.03.2009 и текущей всегда меняющейся даты. И для этого я решил использовать представление даты в Unix TimeStamp, подробнее о котором вы можете узнать в описании конвертера Unix даты. После сведения даты в число остается только вычесть из большего числа меньшее (из числа текущей даты вычитаем число даты 01.03.2009) и перевести время из секунд в годы (обычная математика путем деления).

Так вот, перейдем к реализации. Дабы экономить место, у себя в коде я прописал все компактно одной строкой. Кто не хочет вникать, вот (только замените числа 3, 1 и 2009 на свой месяц, день и год соответственно):

echo floor((time()-mktime(0, 0, 0, 3, 1, 2009))/(60*60*24*365));

Я для тех, кто всетаки хочет понять, что именно написано в этой строке, я распишу все более подробно:

//задаем переменные $month = 3; //месяц от 1 до 12 $day = 1; //день от 1 до 31 $year = 2009; //год $hour = 0; //час от 0 до 23 $minute = 0; //минуты от 0 до 59 $second = 0; //секунды от 0 до 59 //часы, минуты и секунды указывать не обязательно, //поэтому у меня они равны 0, 0, 0 - что соответстует 12 часам ночи ровно //(если, конечно, вам не нужна переделяная точность до часа, минуты, секунды) //формируем unix-число нужной даты на основе заданных выше переменных $get_past_time = mktime($hour, $minute, $second, $month, $day, $year); //получаем unix-число текущей даты $get_current_time = time(); //выполняем математику: вычитаем из $get_current_time число $get_past_time //и перегоняем полученный результат в секундах в годы //(1 минута = 60 секунд, 1 час = 60 минут, 1 сутки = 24 часа, 1 год = 365 дней) //на основе этого получается, что секунды нужно делить на 60*60*24*365 $math_years = ($get_current_time - $get_past_time)/(60*60*24*365); //получаенное не целое число лет округляем в меньшую сторону, //так как нам нужно знать полное количество лет $final_years = floor($math_years); //все, количество лет с отпределенной даты получено //и находится в переменной $final_years - можно выводить echo "Прошло уже более ".(int)$final_years." лет.";

Этот код аналогичен строке, что я написал выше. Разница только в том, что тут описано все детально и пошагово, а там все компактно и одной строкой.

Виталий Жуков 08.07.2014

Все комментарии к заметке «Как посчитать количество лет с определенной даты на PHP»

Источник

Count years from date php

Первое, что нам требуется — это вывести текущий год, это делается, например echo date(‘Y’); и в результате мы получим:

И далее нам остается отнять от данной даты наш год рождения! Это число будет всегда стационарной, я родился в тот год, когда вышла стена pink floyd echo date(‘Y’) -1969; результат:

Но если, вы смотрите на сколько полных мне лет php после 12 мая, то все верно!
Но если , вы смотрите на это число, до 12 мая, то здесь явная ошибка, потому, что мне точно еще нет полных лет!

Давайте разберем эту ошибку и посмотрим возможные варианты

Ошибка сколько полных мне лет

Кстати если вы родились 1 января, то у вас такой ошибки никогда не будет!

Ошибка, которая нас подстерегает, когда мы будем говорить о том сколько полных лет тебе через php? в чем ошибка!?

Представим, что вы родились 12 мая, на схеме это представлено, как 5 часов и красная зона, которая начинается с первого января каждого года до 12 мая каждого когда — будет возникать ошибка, в зависимости от той даты, в которой вы сейчас находитесь!

Ошибка сколько полных мне лет

Если вы находитесь в промежутке времени от 01.01.2023 до 12.05.2023 , то мне еще не стукнуло(echo date(‘Y’)-1969;) полных лет!

Т.е. нам нужно от текущего года отнять единицу, у нас получится вот такая конструкция echo (date(‘Y’) — 1 )-1969; то в этот промежуток времени, мне действительно будет полных лет:

Теперь предположим, что мы находимся в промежутке времени с 12.05.2023 до 31.12.2023 -> то. первый пункт будет верным, а вотром буде ошибка. Что делать!?

Нам нужен скрипт! Который обработает всю эту вакханалию с ошибкой сколько полных мне лет.

Сколько полных мне лет php относительно даты рождения

Нам потребуется число первое января текущего года(превратим дату в метку времени) ->

Вторая метка времени — это будет наш день рождение каждого года ->

И третье число — текущая временная метка -> time() ;

И далее совершенно простое условие, если текущая временная метка находится внутри красной зоны, то отнимаем 1, иначе отнимаем от даты год рождения! Это гениально, профессор! смайлы :

Источник

How to Get Year From a Date in PHP?

New here? Like SchoolsOfWeb on Facebook to stay up to date with new posts.

Problem:

You have a date which consists of day, month, and year. You just want to retrieve the year from that date.

Solution:

There are few ways you can retrieve year from a date. In the following you’ll see different ways to retrieve year from current date or from any date –

Method 1: Using only date() function to get current year

PHP’s date() function can let you know date and time related information based on the formatting string it takes in its first parameter. It can take two parameters. If you use only one parameter, It will return info about the current time.

Depending on the formatting parameter you can get two types of output as the year-

  • Y- A four digit numeric representation of a year. Ex. 2001
  • y – A two digit numeric representation of a year. Ex. 01

Now, see these in action in the example-

"; echo "2 digit of current year is: " . date("y"); ?>

Output:
4 digit of current year is: 2014
2 digit of current year is: 14

Method 2: Using strtotime() and date() function to get year from any date

In this method, to get the year, we’ll follow two steps-

  • We’ll first convert a date to its equivalent timestamp using strtotime() function. A timestamp of a date is the representation of seconds from January 1 1970 00:00:00 UTC to that time, then,
  • We’ll use the date() function that we used in the method 1.

See how it works in action in the following example-

"; echo "2 digit of current year is: " . date("y", $timestamp); ?>

Output:
4 digit of current year is: 1993
2 digit of current year is: 93

In the above example,I used 5th February 1993 as date format. You may have different date format. Don’t worry. Any format will work as long as you follow the supported date and time formats

Method 3: Using DateTime class to get current year

From PHP 5.2, PHP provides some ready-made classes to solve daily problems. One of the classes is DateTime which helps to solve date time related issues.

To get current year using DateTime class, we’ll follow two steps-

  • Create an object of DateTime class. The DateTIme() class represents the current time.
  • Then, use format() method to retrieve the year from the newly created object.

See the following example-

format('Y'); echo "
"; echo "2 digit of current year is: " . $now->format('y'); ?>

Output:
4 digit of current year is: 2014
2 digit of current year is: 14

Method 4: Using CreateFromFormat() method to get year from any date

In this method, we’ll retrieve year from any date in two steps-

  • First, we’ll create a new DateTime object from the date using createFromFormat() method, then
  • Then, we’ll retrieve the year using format() method

See it in action in the following example –

format('Y'); echo "
"; echo "2 digit of current year is: " . $dateObj->format('y'); ?>

Output:
4 digit of current year is: 1993
2 digit of current year is: 93

Источник

Оцените статью