Php date sub hour

Php date sub hour

  • PHP Tutorial
  • PHP | Introduction
  • PHP Full Form
  • How to set PHP development environment in windows ?
  • LAMP installation and important PHP configurations on Ubuntu
  • PHP | Coding Standards
  • PHP | Basic Syntax
  • PHP | Variables
  • PHP echo and print
  • PHP | Data Types
  • PHP | Strings
  • PHP | Constants
  • PHP | Magic Constants
  • PHP | Decision Making
  • PHP | Loops
  • PHP | Superglobals
  • PHP | Regular Expressions
  • PHP Examples
  • Describe PHP Include and Require
  • PHP | Basics of File Handling
  • PHP | fopen( ) (Function open file or URL)
  • PHP fread( ) Function
  • PHP fclose( ) Function
  • PHP | fwrite( ) Function
  • PHP | Uploading File
  • PHP Cookies
  • PHP | Sessions
  • PHP Filter and Filter Constant
  • Implementing callback in PHP
  • Exception Handling in PHP
  • PHP | Arrays
  • PHP array() Function
  • PHP | array_change_key_case() Function
  • PHP array_chunk() Function
  • PHP | array_column() Function
  • PHP array_combine() Function
  • PHP array_count_values() Function
  • PHP array_diff() function
  • PHP array_diff_assoc() Function
  • PHP array_diff_key() Function
  • PHP array_diff_uassoc() Function
  • PHP array_diff_ukey() Function
  • PHP array_fill() function
  • PHP array_fill_keys() Function
  • PHP Array Functions Complete Reference
  • PHP Date and Time
  • PHP | checkdate() Function
  • PHP | date_create(), date_format(), date_add() Functions
  • PHP | date_create_from_format() Function
  • PHP | date_date_set() Function
  • PHP | date_default_timezone_get() Function
  • PHP | date_default_timezone_set() Function
  • PHP | date_diff() Function
  • PHP | date_get_last_errors() Function
  • PHP | date_isodate_set() Function
  • PHP | date_modify() Function
  • PHP | date_offset_get() Function
  • PHP | date_parse_from_format() Function
  • PHP | date_parse() Function
  • PHP | date_sub() Function
  • PHP basename( ) Function
  • PHP chgrp( ) Function
  • PHP chmod( ) Function
  • PHP chown( ) Function
  • PHP copy( ) Function
  • PHP dirname( ) Function
  • PHP disk_free_space( ) Function
  • PHP disk_total_space( ) Function
  • PHP feof( ) Function
  • PHP fflush( ) Function
  • PHP | fgetc( ) Function
  • PHP | fgets( ) Function
  • PHP | fgetss( ) Function
  • PHP | file_exists( ) Function
  • PHP file_get_contents() Function
  • PHP Filesystem Functions Complete Reference
  • PHP | ftp_alloc() function
  • PHP | ftp_chdir() function
  • PHP | ftp_close() function
  • PHP | ftp_connect() function
  • PHP | ftp_delete() function
  • PHP | ftp_exec() function
  • PHP | ftp_get() function
  • PHP | ftp_put() function
  • PHP | ftp_get_option() function
  • PHP | ftp_login() function
  • PHP | ftp_mdtm() Function
  • PHP | ftp_mkdir() function
  • PHP | Ds\Map allocate() Function
  • PHP | Ds\Map apply() Function
  • PHP | Ds\Map capacity() Function
  • PHP | DS\Map clear() Function
  • PHP | Ds\Map __construct() Function
  • PHP Ds\Map copy() Function
  • PHP | Ds\Map count() Function
  • PHP | Ds\Map diff() Function
  • PHP | Ds\Map filter() Function
  • PHP | Ds\Map first() Function
  • PHP Ds\Map Functions Complete Reference
  • SplDoublyLinkedList in PHP
  • PHP SplDoublyLinkedList add() Function
  • PHP SplDoublyLinkedList bottom() Function
  • PHP SplDoublyLinkedList count() function
  • PHP SplFixedArray count() Function
  • PHP SplFixedArray current() Function
  • PHP SplFixedArray getSize() Function
  • PHP SplFixedArray key() Function
  • PHP SplObjectStorage addAll() Function
  • PHP SplObjectStorage attach() Function
  • PHP SplObjectStorage contains() Function
  • PHP SplObjectStorage count() Function
  • PHP SplQueue::__construct() Function
  • PHP SPL Data structures Complete Reference
  • PHP Tutorial
  • PHP | Introduction
  • PHP Full Form
  • How to set PHP development environment in windows ?
  • LAMP installation and important PHP configurations on Ubuntu
  • PHP | Coding Standards
  • PHP | Basic Syntax
  • PHP | Variables
  • PHP echo and print
  • PHP | Data Types
  • PHP | Strings
  • PHP | Constants
  • PHP | Magic Constants
  • PHP | Decision Making
  • PHP | Loops
  • PHP | Superglobals
  • PHP | Regular Expressions
  • PHP Examples
  • Describe PHP Include and Require
  • PHP | Basics of File Handling
  • PHP | fopen( ) (Function open file or URL)
  • PHP fread( ) Function
  • PHP fclose( ) Function
  • PHP | fwrite( ) Function
  • PHP | Uploading File
  • PHP Cookies
  • PHP | Sessions
  • PHP Filter and Filter Constant
  • Implementing callback in PHP
  • Exception Handling in PHP
  • PHP | Arrays
  • PHP array() Function
  • PHP | array_change_key_case() Function
  • PHP array_chunk() Function
  • PHP | array_column() Function
  • PHP array_combine() Function
  • PHP array_count_values() Function
  • PHP array_diff() function
  • PHP array_diff_assoc() Function
  • PHP array_diff_key() Function
  • PHP array_diff_uassoc() Function
  • PHP array_diff_ukey() Function
  • PHP array_fill() function
  • PHP array_fill_keys() Function
  • PHP Array Functions Complete Reference
  • PHP Date and Time
  • PHP | checkdate() Function
  • PHP | date_create(), date_format(), date_add() Functions
  • PHP | date_create_from_format() Function
  • PHP | date_date_set() Function
  • PHP | date_default_timezone_get() Function
  • PHP | date_default_timezone_set() Function
  • PHP | date_diff() Function
  • PHP | date_get_last_errors() Function
  • PHP | date_isodate_set() Function
  • PHP | date_modify() Function
  • PHP | date_offset_get() Function
  • PHP | date_parse_from_format() Function
  • PHP | date_parse() Function
  • PHP | date_sub() Function
  • PHP basename( ) Function
  • PHP chgrp( ) Function
  • PHP chmod( ) Function
  • PHP chown( ) Function
  • PHP copy( ) Function
  • PHP dirname( ) Function
  • PHP disk_free_space( ) Function
  • PHP disk_total_space( ) Function
  • PHP feof( ) Function
  • PHP fflush( ) Function
  • PHP | fgetc( ) Function
  • PHP | fgets( ) Function
  • PHP | fgetss( ) Function
  • PHP | file_exists( ) Function
  • PHP file_get_contents() Function
  • PHP Filesystem Functions Complete Reference
  • PHP | ftp_alloc() function
  • PHP | ftp_chdir() function
  • PHP | ftp_close() function
  • PHP | ftp_connect() function
  • PHP | ftp_delete() function
  • PHP | ftp_exec() function
  • PHP | ftp_get() function
  • PHP | ftp_put() function
  • PHP | ftp_get_option() function
  • PHP | ftp_login() function
  • PHP | ftp_mdtm() Function
  • PHP | ftp_mkdir() function
  • PHP | Ds\Map allocate() Function
  • PHP | Ds\Map apply() Function
  • PHP | Ds\Map capacity() Function
  • PHP | DS\Map clear() Function
  • PHP | Ds\Map __construct() Function
  • PHP Ds\Map copy() Function
  • PHP | Ds\Map count() Function
  • PHP | Ds\Map diff() Function
  • PHP | Ds\Map filter() Function
  • PHP | Ds\Map first() Function
  • PHP Ds\Map Functions Complete Reference
  • SplDoublyLinkedList in PHP
  • PHP SplDoublyLinkedList add() Function
  • PHP SplDoublyLinkedList bottom() Function
  • PHP SplDoublyLinkedList count() function
  • PHP SplFixedArray count() Function
  • PHP SplFixedArray current() Function
  • PHP SplFixedArray getSize() Function
  • PHP SplFixedArray key() Function
  • PHP SplObjectStorage addAll() Function
  • PHP SplObjectStorage attach() Function
  • PHP SplObjectStorage contains() Function
  • PHP SplObjectStorage count() Function
  • PHP SplQueue::__construct() Function
  • PHP SPL Data structures Complete Reference
Читайте также:  Python string to binary format

Источник

PHP date_sub() Function

The date_sub() function subtracts some days, months, years, hours, minutes, and seconds from a date.

Syntax

Parameter Values

Parameter Description
object Required. Specifies a DateTime object returned by date_create()
interval Required. Specifies a DateInterval object

Technical Details

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Subtract hours from a time and date using PHP.

In this tutorial, we are going to show you how to subtract hours from a date and time using PHP.

This can be useful if you need to work out an exact date and time in the recent past.

For example, “What time was it six hours ago?” or “What time was it twelve hours ago?”

Subtracting hours using PHP’s time function.

You can subtract hours using PHP’s time function and some basic arithmetic:

//Get the current timestamp. $currentTime = time(); //The number of hours that you want //to subtract from the date and time. $hoursToSubtract = 12; //Convert those hours into seconds so //that we can subtract them from our timestamp. $timeToSubtract = ($hoursToSubtract * 60 * 60); //Subtract the hours from our Unix timestamp. $timeInPast = $currentTime - $timeToSubtract; //Print it out in a human-readable format. echo date("d/m/y H:i", $timeInPast) . ' was ' . $hoursToSubtract . ' hours ago.';

An explanation of the PHP code above:

  1. We got the current Unix timestamp using PHP’s time function.
  2. We defined a variable called $hoursToSubtract. This variable contains the number of hours that we want to subtract from our date and time.
  3. After that, we converted our hours into seconds by multiplying them by 3600. This works because there are exactly 3600 seconds in one hour (60 x 60 = 3600). In the case above, 12 x 3600 = 43200.
  4. Finally, we subtracted those seconds from our timestamp and then printed out the result in a human friendly date format.

When we ran the example above at 14:52 p.m. on January 9th, 2020, the output was:

As you can see, this is correct, as 12 hours before 14:52PM was 2:52AM.

Using PHP’s DateTime object to subtract hours from a date.

You can also use PHP’s DateTime object to subtract hours from a given date and time.

Take the following example:

//Get the current timestamp. $current = new DateTime(); //The number of hours to subtract. $hoursToSubtract = 12; //Subtract the hours by using the DateTime::sub method. $current->sub(new DateInterval("PTH")); //Format the new time. $newTime = $current->format('Y-m-d H:i'); echo $newTime;

In the example above, we used the DateTime::sub method to subtract a period of 12 hours from the current timestamp.

Essentially, we passed in a DateInterval object with PT12H as the $interval_spec parameter.

PT12H basically means “a period of time of 12 hours.” If you want to subtract 24 instead of 12, you can use PT24H.

If you want to subtract hours from a given date, you can do the following:

//Datetime object for a given date. $dT = new DateTime("2020-01-09 01:00:00"); //Lets subtract 4 hours. $hoursToSubtract = 4; //Subtract the hours using DateTime::sub and DateInterval. $dT->sub(new DateInterval("PTH")); //Format and print it out. $newTime = $dT->format('Y-m-d H:i'); echo $newTime;

If you run the DateTime code above, you will see that the output is “2020-01-08 21:00”.

This is correct, as 2020-01-08 21:00 occurred exactly four hours before 2020-01-09 01:00.

Источник

date_sub

Вычитает из времени объекта DateTime заданный интервал DateInterval.

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

Только для процедурного стиля: Объект DateTime, возвращаемый date_create() . Функция изменяет этот объект.

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

Возвращает объект DateTime для применения в цепи методов или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования DateTime::sub()

$date = new DateTime ( ‘2000-01-20’ );
$date -> sub (new DateInterval ( ‘P10D’ ));
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;
?>

$date = date_create ( ‘2000-01-20’ );
date_sub ( $date , date_interval_create_from_date_string ( ’10 days’ ));
echo date_format ( $date , ‘Y-m-d’ );
?>

Результат выполнения данных примеров:

Пример #2 Другие примеры DateTime::sub()

$date = new DateTime ( ‘2000-01-20’ );
$date -> sub (new DateInterval ( ‘PT10H30S’ ));
echo $date -> format ( ‘Y-m-d H:i:s’ ) . «\n» ;

$date = new DateTime ( ‘2000-01-20’ );
$date -> sub (new DateInterval ( ‘P7Y5M4DT4H3M2S’ ));
echo $date -> format ( ‘Y-m-d H:i:s’ ) . «\n» ;
?>

Результат выполнения данного примера:

2000-01-19 13:59:30 1992-08-15 19:56:58

Пример #3 Будьте внимательны при вычитании месяцев

$date = new DateTime ( ‘2001-04-30’ );
$interval = new DateInterval ( ‘P1M’ );

$date -> sub ( $interval );
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;

$date -> sub ( $interval );
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;
?>

Результат выполнения данного примера:

Примечания

При работе с PHP 5.2 в качестве альтернативы можно использовать функцию DateTime::modify() .

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

  • DateTime::add() — Добавляет заданное количество дней, месяцев, лет, часов, минут и секунд к объекту DateTime
  • DateTime::diff() — Возвращает разницу между двумя DateTime объектами
  • DateTime::modify() — Изменение временной метки

Источник

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