Php one year from now

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.

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

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.

Читайте также:  Fizzbuzz python sololearn решение

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 15th July (2023-07-15) last Saturday Saturday 22nd July (2023-07-22) Saturday Saturday 29th July (2023-07-29) this Saturday Saturday 29th July (2023-07-29) first Saturday Saturday 29th July (2023-07-29) next Saturday Saturday 29th July (2023-07-29) third Saturday Saturday 12th August (2023-08-12) +2 weeks Saturday Saturday 12th August (2023-08-12)

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 Sunday we can run the following:

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

You can see in the table above that, while ‘next Sunday’ 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 19th July (2023-07-19) -2 days last Saturday Thursday 20th July (2023-07-20) yesterday last Saturday Friday 21st July (2023-07-21) tomorrow Saturday Sunday 30th July (2023-07-30) +2 days Saturday Monday 31st July (2023-07-31) +3 days Saturday Tuesday 1st August (2023-08-01)

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

Источник

date

Возвращает строку, отформатированную в соответствии с указанным в параметре format шаблоном. Используется метка времени, заданная параметром timestamp (метка времени Unix), или текущее системное время, если параметр timestamp не задан. Таким образом, параметр timestamp является необязательным и по умолчанию равен значению, возвращаемому функцией time() .

Метки времени Unix не обрабатывают часовые пояса. Используйте класс DateTimeImmutable и его метод форматирования DateTimeInterface::format() для форматирования информации о дате/времени с привязкой к часовому поясу.

Список параметров

Замечание: Функция date() всегда будет генерировать 000000 в качестве микросекунд, поскольку она принимает параметр int , тогда как DateTime::format() поддерживает микросекунды, если DateTime был создан с микросекундами.

Необязательный параметр timestamp представляет собой метку времени типа int , по умолчанию равную текущему локальному времени, если timestamp не указан или null . Другими словами, значение по умолчанию равно результату функции time() .

Возвращаемые значения

Возвращает отформатированную строку с датой.

Ошибки

Каждый вызов к функциям даты/времени при неправильных настройках часового пояса сгенерирует ошибку уровня E_WARNING , если часовой пояс некорректный. Смотрите также date_default_timezone_set()

Список изменений

Версия Описание
8.0.0 timestamp теперь допускает значение null.

Примеры

Пример #1 Примеры использования функции date()

// установка часового пояса по умолчанию.
date_default_timezone_set ( ‘UTC’ );

// выведет примерно следующее: Monday
echo date ( «l» );

// выведет примерно следующее: Monday 8th of August 2005 03:12:46 PM
echo date ( ‘l jS \of F Y h:i:s A’ );

// выведет: July 1, 2000 is on a Saturday
echo «July 1, 2000 is on a » . date ( «l» , mktime ( 0 , 0 , 0 , 7 , 1 , 2000 ));

/* пример использования константы в качестве форматирующего параметра */
// выведет примерно следующее: Mon, 15 Aug 2005 15:12:46 UTC
echo date ( DATE_RFC822 );

// выведет примерно следующее: 2000-07-01T00:00:00+00:00
echo date ( DATE_ATOM , mktime ( 0 , 0 , 0 , 7 , 1 , 2000 ));
?>

Чтобы запретить распознавание символа как форматирующего, следует экранировать его с помощью обратного слеша. Если экранированный символ также является форматирующей последовательностью, то следует экранировать его повторно.

Пример #2 Экранирование символов в функции date()

Для вывода прошедших и будущих дат удобно использовать функции date() и mktime() .

Пример #3 Пример совместного использования функций date() и mktime()

$tomorrow = mktime ( 0 , 0 , 0 , date ( «m» ) , date ( «d» )+ 1 , date ( «Y» ));
$lastmonth = mktime ( 0 , 0 , 0 , date ( «m» )- 1 , date ( «d» ), date ( «Y» ));
$nextyear = mktime ( 0 , 0 , 0 , date ( «m» ), date ( «d» ), date ( «Y» )+ 1 );
?>

Замечание:

Данный способ более надёжен, чем простое вычитание и прибавление секунд к метке времени, поскольку позволяет при необходимости гибко осуществить переход на летнее/зимнее время.

Ещё несколько примеров использования функции date() . Важно отметить, что следует экранировать все символы, которые необходимо оставить без изменений. Это справедливо и для тех символов, которые в текущей версии PHP не распознаются как форматирующие, поскольку это может быть введено в следующих версиях. Для экранировании управляющих последовательностей (например, \n) следует использовать одинарные кавычки.

Пример #4 Форматирование с использованием date()

// Предположим, что текущей датой является 10 марта 2001, 5:16:18 вечера,
// и мы находимся в часовом поясе Mountain Standard Time (MST)

$today = date ( «F j, Y, g:i a» ); // March 10, 2001, 5:16 pm
$today = date ( «m.d.y» ); // 03.10.01
$today = date ( «j, n, Y» ); // 10, 3, 2001
$today = date ( «Ymd» ); // 20010310
$today = date ( ‘h-i-s, j-m-y, it is w Day’ ); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date ( ‘\i\t \i\s \t\h\e jS \d\a\y.’ ); // it is the 10th day.
$today = date ( «D M j G:i:s T Y» ); // Sat Mar 10 17:16:18 MST 2001
$today = date ( ‘H:m:s \m \i\s\ \m\o\n\t\h’ ); // 17:03:18 m is month
$today = date ( «H:i:s» ); // 17:16:18
$today = date ( «Y-m-d H:i:s» ); // 2001-03-10 17:16:18 (формат MySQL DATETIME)
?>

Для форматирования дат на других языках вместо функции date() можно использовать метод IntlDateFormatter::format() .

Примечания

Замечание:

Для получения метки времени из строкового представления даты можно воспользоваться функцией strtotime() . Кроме того, некоторые базы данных имеют собственные функции для преобразования внутреннего представления даты в метку времени (например, функция MySQL » UNIX_TIMESTAMP).

Временную метку начала запроса можно получить из поля $_SERVER[‘REQUEST_TIME’] .

Смотрите также

  • DateTimeImmutable::__construct() — Возвращает новый объект DateTimeImmutable
  • DateTimeInterface::format() — Возвращает дату, отформатированную согласно переданному формату
  • gmdate() — Форматирует дату/время по Гринвичу
  • idate() — Преобразует локальное время/дату в целое число
  • getdate() — Возвращает информацию о дате/времени
  • getlastmod() — Получает время последней модификации страницы
  • mktime() — Возвращает метку времени Unix для заданной даты
  • IntlDateFormatter::format() — Форматирует значение даты/времени в виде строки
  • time() — Возвращает текущую метку системного времени Unix
  • Предопределённые константы даты и времени

User Contributed Notes

  • Функции даты и времени
    • checkdate
    • date_​add
    • date_​create_​from_​format
    • date_​create_​immutable_​from_​format
    • date_​create_​immutable
    • date_​create
    • date_​date_​set
    • date_​default_​timezone_​get
    • date_​default_​timezone_​set
    • date_​diff
    • date_​format
    • date_​get_​last_​errors
    • date_​interval_​create_​from_​date_​string
    • date_​interval_​format
    • date_​isodate_​set
    • date_​modify
    • date_​offset_​get
    • date_​parse_​from_​format
    • date_​parse
    • date_​sub
    • date_​sun_​info
    • date_​sunrise
    • date_​sunset
    • date_​time_​set
    • date_​timestamp_​get
    • date_​timestamp_​set
    • date_​timezone_​get
    • date_​timezone_​set
    • date
    • getdate
    • gettimeofday
    • gmdate
    • gmmktime
    • gmstrftime
    • idate
    • localtime
    • microtime
    • mktime
    • strftime
    • strptime
    • strtotime
    • time
    • timezone_​abbreviations_​list
    • timezone_​identifiers_​list
    • timezone_​location_​get
    • timezone_​name_​from_​abbr
    • timezone_​name_​get
    • timezone_​offset_​get
    • timezone_​open
    • timezone_​transitions_​get
    • timezone_​version_​get

    Источник

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