Php date вчерашний день

Get timestamp of today and yesterday in php

How can I get the timestamp of 12 o’clock of today, yesterday and the day before yesterday by using strtotime() function in php? 12 o’clock is a variable and would be changed by user.

Depends on how you store the 12 o’clock (hours, minutes, seconds?). In general, did you have a look at the functions listed in (php.net/manual/en/book.datetime.php)? What did you try so far?

definite duplicate of getting timestamp in php — You already asked that yesterday. The only difference is the arguments you pass to these functions. You can find the possible relative formats in the PHP Manual

@Gordon: i am sorry.i am really stupid today.i wanted to delete it but it has some answer now and i can’t delete it.

9 Answers 9

$hour = 12; $today = strtotime($hour . ':00:00'); $yesterday = strtotime('-1 day', $today); $dayBeforeYesterday = strtotime('-1 day', $yesterday); 

@Hannes Then I’d prefer $hour . ‘:00:00’ . If you don’t need variable interpolation, use single quotes. :o)

Читайте также:  Пример CSS

strtotime(): It is not safe to rely on the system’s timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function

strtotime supports a number of interesting modifiers that can be used:

$hour = 12; $today = strtotime("today $hour:00"); $yesterday = strtotime("yesterday $hour:00"); $dayBeforeYesterday = strtotime("yesterday -1 day $hour:00"); echo date("Y-m-d H:i:s\n", $today); echo date("Y-m-d H:i:s\n", $yesterday); echo date("Y-m-d H:i:s\n", $dayBeforeYesterday); 
2011-01-24 12:00:00 2011-01-23 12:00:00 2011-01-22 12:00:00 
$iHour = 12; $oToday = new DateTime(); $oToday->setTime($iHour, 0); $oYesterday = clone $oToday; $oYesterday->modify('-1 day'); $oDayBefore = clone $oYesterday; $oDayBefore->modify('-1 day'); $iToday = $oToday->getTimestamp(); $iYesterday = $oYesterday->getTimestamp(); $iDayBefore = $oDayBefore->getTimestamp(); echo "Today: $iToday\n"; echo "Yesterday: $iYesterday\n"; echo "Day Before: $iDayBefore\n"; 

You can easily find out any date using DateTime object, It is so flexible

$yesterday = new DateTime('yesterday'); echo $yesterday->format('Y-m-d'); $firstModayOfApril = new DateTime('first monday of april'); echo $firstModayOfApril->format('Y-m-d'); $nextMonday = new DateTime('next monday'); echo $nextMonday->format('Y-m-d'); 

to get start of day yesterday

$oDate = new DateTime(); $oDate->modify('-1 day'); echo $oDate->format('Y-m-d 00:00:00'); 

All the answers here are too long and bloated, everyone loves one-lines 😉

$yesterday = Date('Y-m-d', strtotime('-1 day')); 

(Or if you are American you can randomize the date unit order to m/d/y (or whatever you use) and use Cups, galloons, feet and horses as units. )

Источник

Дата вчера сегодня завтра (PHP)

Для получения даты в PHP используется функция date(string $format[, int $timestamp = time()]) , которая возвращает дату отформатированную в соответствии с шаблоном string $format .

Например сегодня: 19 ноября 2013г.

Дата сегодня

Чтобы вывести дату в формате ГГГГ-ММ-ДД , достаточно выполнить следующий код.

Чтобы получить дату отличную от сегодняшнего дня, необходимо вторым параметров передать время в секундах, получаемое при помощи функции int time() , и прибавить/отнять нужное количество секунд.

Дата вчера

Например, чтобы получить вчерашнюю дату, необходимо от значения time() отнять 1 день в секундах.

В одном дне 60 * 60 * 24 = 86400 секунд .

Дата завтра

Чтобы получить дату завтрашнего дня, соответственно, необходимо прибавить 1 день (или 86400 секунд).

Дата послезавтра

Получить дату за послезавтра, необходимо прибавить 2 дня (2 умноженное на 86400 секунд).

Дата послезавтра

Дату за позавчера — необходимо отнять 2 дня (2 умноженное на 86400 секунд).

Категории

Читайте также

  • Установить часовой пояс (PHP)
  • Как узнать день недели (JavaScript)
  • Как получить TIMESTAMP дня текущей недели (PHP)
  • Количество секунд от начала дня (PHP)
  • Конвертировать миллисекунды в time.Time (GoLang)
  • Преобразовать дату в секунды (PHP)
  • Время выполнения скрипта (PHP)
  • Название предыдущего месяца (PHP)
  • Количество секунд между датами (PHP)
  • Количество минут между датами (PHP)
  • Количество дней между датами (PHP)
  • Количество часов между датами (PHP)

Комментарии

Илья, смотрите более подробно функции setlocale() и strftime().

Здравствуйте!
Подскажите, а как сделать дату такого формата 14 ноября 2015 г. ?

А разве это как-то повлияет на вычисление даты? 🙂

> В одном дне 60 * 60 * 24 = 86400 секунд.
А в дни, когда часы переводятся на час вперед или назад?

Вход на сайт

Введите данные указанные при регистрации:

Социальные сети

Вы можете быстро войти через социальные сети:

Источник

PHP date yesterday [duplicate]

date() itself is only for formatting, but it accepts a second parameter.

date("F j, Y", time() - 60 * 60 * 24); 

To keep it simple I just subtract 24 hours from the unix timestamp.

A modern oop-approach is using DateTime

$date = new DateTime(); $date->sub(new DateInterval('P1D')); echo $date->format('F j, Y') . "\n"; 

Or in your case (more readable/obvious)

$date = new DateTime(); $date->add(DateInterval::createFromDateString('yesterday')); echo $date->format('F j, Y') . "\n"; 

(Because DateInterval is negative here, we must add() it here)

very good answer, there are many ways to do it but you have the simple one, short and easy to understand ( + the OOP one for those interested in using more RAM 😉

@neofutur Beside «we want to waste our RAM» the OOP-approach is useful, when you already have either a DateTime -, or a DateInterval -object (or both), which may be the case in an OOP-based application (e.g. $customer->expire->add(DateInterval::createFromDateString(‘+1 year’)) // customer paid for one additional year ) Also note, that DateInterval understands ISO8601 for time intervals, but date() doesn’t. At the end of course: Select the one you better fit your needs 🙂

This is NOT a correct answer!! Daylight savings makes 23 and 25 hour days. So this is NOT giving you a good answer 2 hours of the year.

@patrick Interesting point 🙂 Yes, you are right, but this is only true for the first solution, not the following utilizing DateInterval .

Источник

Get Yesterday’s Date in PHP

Get Yesterday

  1. date() in PHP
  2. DateInterval in PHP
  3. Using strtotime() to Get Yesterday’s Date in PHP
  4. Using mktime() to Get Yesterday’s Date in PHP
  5. Using time() to Get Yesterday’s Date in PHP
  6. Using DateInterval to Get Yesterday’s Date in PHP

This article will introduce how to get yesterday’s date in PHP.

Before learning the solution, let’s understand the concept of date().

date() in PHP

It is a built-in PHP function that returns the formatted date string.

Syntax of date()

Parameters

format : This is a mandatory parameter that specifies the output date string format. Some of the options are:

  1. d — The day of the month in the range of 01 to 31
  2. D — A text representation of a day (three letters)
  3. m — A numeric representation of a month in the range of 01 to 12
  4. M — A text representation of a month (three letters)
  5. Y — A four-digit representation of a year
  6. y — A two-digit representation of a year
  7. a — Lowercase am or pm
  8. A — Uppercase AM or PM

timestamp : It is an optional parameter that specifies a Unix timestamp in integer format. If not provided, a default value will be taken as the current local time.

DateInterval in PHP

It is a Class of PHP that represents a date interval. It also provides the static method, which accepts the input strings and sets up a DateInterval from the input string.

Now that we have understood the basic concept of date() , strtotime() and mktime() . We’ll use all of these functions to get the date of yesterday.

Using strtotime() to Get Yesterday’s Date in PHP

strtotime() is a built-in PHP function parses an English textual DateTime into a Unix timestamp from January 1, 1970, 00:00:00 GMT.

Syntax of strtotime()

Parameter

  • time : This is a mandatory parameter, which specifies a date/time string.
  • now : This is an optional parameter, specifying the timestamp used as the basis for calculating relative dates.

We can pass either yesterday or -1 days to the strtotime function to get yesterday’s timestamp. As introduced above, the timestamp can be converted to the date in the string format by the date() function.

php  // Get yesterdays date  echo date('d.m.Y',strtotime("-1 days")). "\n";  echo date('d M Y',strtotime("yesterday")); ?> 

Using mktime() to Get Yesterday’s Date in PHP

It is a built-in PHP function that returns the Unix timestamp for a date. This function is almost the same as gmmktime() except the passed parameters represent a date (not a GMT date).

Syntax

mktime(hour, minute, second, month, day, year) 

Parameter

  • hour : This is an optional parameter, which specifies the hour.
  • minute : It is an optional parameter, which specifies the minute.
  • second : It is an optional parameter, which specifies the second.
  • month : It is an optional parameter, which specifies the month.
  • day : It is an optional parameter, which specifies the day.
  • year : It is an optional parameter, which specifies the year.
php  $m = date("m"); // Month value  $de = date("d"); // Today's date  $y = date("Y"); // Year value   echo "Yesterday's date was: " . date('d-m-Y', mktime(0,0,0,$m,($de-1),$y)); ?> 
Yesterday's date was: 24-10-2021 

The values of year and month are the same between today and yesterday. The day value of yesterday is one less than that of today.

Using time() to Get Yesterday’s Date in PHP

The time() function returns the current timestamp. If we subtract its value, then we get the timestamp of the same time yesterday.

php  echo date('d M Y', time() - 60 * 60 * 24); ?> 

Using DateInterval to Get Yesterday’s Date in PHP

It is a Class of PHP that represents a date interval. It also provides the static method, which accepts the input strings and sets up a DateInterval from the input string.

Syntax of DateInterval()

Parameter

  1. P$numberD — A time in the form of day. $number is in the range of 1-31.
  2. P$numberM — A time in the form of the month. $number is in the range of 1-12.
  3. P$numberY — A Time in the form of the year. $number is in the range of 1-100.
  4. PT$numberH — A Time in the form of an hour. $number is in the range of 1-24.
  5. PT$numberM — A Time in the form of a minute. $number is in the range of 0-60.
  6. PT$numberS — A Time in the form of the second. $number is in the range of 0-60.

Syntax of DateInterval::createFromDateString()

public static DateInterval::createFromDateString(string $datetime); 

Parameter

$datetime : It is a mandatory parameter that specifies the date/time in string format.

We can pass yesterday to the createFromDateString() and P1D to the DateInterval function to get yesterday’s timestamp. We can add or subtract this timestamp from the current timestamp, and the resulted timestamp can be converted to the date in the string format by the date() function.

php  $date = new DateTime();  $date->add(DateInterval::createFromDateString('yesterday'));  echo $date->format('d M Y') . "\n";   $date = new DateTime();  $date->sub(new DateInterval('P1D'));  echo $date->format('d M Y') . "\n"; ?> 

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

Related Article — PHP Date

Источник

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