Datetime php set hours

PHP DateTime

Summary: in this tutorial, you’ll learn how to work with the date and time in an object-oriented way.

Introduction to the PHP DateTime class

PHP provides a set of date and time classes that allow you to work with the date and time in an object-oriented way.

To create a new date and time object, you use the DateTime class. For example:

 $datetime = new DateTime(); var_dump($datetime);Code language: PHP (php)
object(DateTime)#1 (3) ["date"]=> string(26) "2021-07-15 06:30:40.294788" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" >Code language: PHP (php)

The DateTime object represents the current date and time in the timezone specified in the PHP configuration file ( php.ini )

To set a new timezone, you create a new DateTimeZone object and pass it to the setTimezone() method of the DateTime object:

 $datetime = new DateTime(); $timezone = new DateTimeZone('America/Los_Angeles'); $datetime->setTimezone($timezone); var_dump($datetime);Code language: PHP (php)
object(DateTime)#1 (3) ["date"]=> string(26) "2021-07-14 21:33:27.986925" ["timezone_type"]=> int(3) ["timezone"]=> string(19) "America/Los_Angeles" >Code language: PHP (php)

In this example, we create a new DateTimeZone object and set it to «America/Los_Angeles» . To get valid timezones supported by PHP, check out the timezone list.

To format a DateTime object, you use the format() method. The format string parameters are the same as those you use for the date() function. For example:

 $datetime = new DateTime(); echo $datetime->format('m/d/Y g:i A'); Code language: PHP (php)
07/15/2021 6:38 AMCode language: PHP (php)

To set a specific date and time, you can pass a date & time string to the DateTime() constructor like this:

 $datetime = new DateTime('12/31/2019 12:00 PM'); echo $datetime->format('m/d/Y g:i A');Code language: PHP (php)

Or you can use the setDate() function to set a date:

 $datetime = new DateTime(); $datetime->setDate(2020, 5, 1); echo $datetime->format('m/d/Y g:i A');Code language: PHP (php)
05/01/2020 6:42 AMCode language: PHP (php)

The time is derived from the current time. To set the time, you use the setTime() function:

 $datetime = new DateTime(); $datetime->setDate(2020, 5, 1); $datetime->setTime(5, 30, 0); echo $datetime->format('m/d/Y g:i A');Code language: PHP (php)
05/01/2020 5:30 AMCode language: PHP (php)

Since the setDate() , setTime() , and setTimeZone() method returns the DateTime object, you can chain them like this which is quite convenient.

 $datetime = new DateTime(); echo $datetime->setDate(2020, 5, 1) ->setTime(5, 30) ->setTimezone(new DateTimeZone('America/New_York')) ->format('m/d/Y g:i A');Code language: PHP (php)
04/30/2020 11:30 PMCode language: PHP (php)

Creating a DateTime object from a string

When you pass the date string ’06/08/2021′ to the DateTime() constructor or setDate() function, PHP interprets it as m/d/Y . For example:

 $datetime = new DateTime('06/08/2021'); echo $datetime->format('F jS, Y'); Code language: PHP (php)
June 8th, 2021Code language: PHP (php)

If you want to pass it as August 6th, 2021, you need to use the – or . instead of /. For example:

 $datetime = new DateTime('06-08-2021'); echo $datetime->format('F jS, Y');Code language: PHP (php)
August 6th, 2021Code language: PHP (php)

However, if you want to parse the date string ’06/08/2021′ as d/m/Y, you need to replace the / with – or . manually:

 $ds = '06/08/2021'; $datetime = new DateTime(str_replace('/', '-', $ds)); echo $datetime->format('F jS, Y');Code language: PHP (php)
August 6th, 2021Code language: PHP (php)

A better way to do it is to use the createFromFormat() static method of the DateTime object:

 $ds = '06/08/2021'; $datetime = DateTime::createFromFormat('d/m/Y', $ds); echo $datetime->format('F jS, Y');Code language: PHP (php)

In this example, we pass the date format as the first argument and the date string as the second argument.

Note that when you pass a date string without the time, the DateTime() constructor uses midnight time. However, the createFromFormat() method uses the current time.

Comparing two DateTime objects

PHP allows you to compare two DateTime objects using the comparison operators including >, >=, . For example:

 $datetime1 = new DateTime('01/01/2021 10:00 AM'); $datetime2 = new DateTime('01/01/2021 09:00 AM'); var_dump($datetime1 < $datetime2); // false var_dump($datetime1 > $datetime2); // true var_dump($datetime1 == $datetime2); // false var_dump($datetime1 $datetime2); // 1Code language: PHP (php)

Calculating the differences between two DateTime objects

The diff() method of the DateTime() object returns the difference between two DateTime() objects as a DateInterval object. For example:

 $dob = new DateTime('01/01/1990'); $to_date = new DateTime('07/15/2021'); $age = $to_date->diff($dob); var_dump($age);Code language: PHP (php)
object(DateInterval)#3 (16) ["y"]=> int(31) ["m"]=> int(6) ["d"]=> int(14) ["h"]=> int(0) ["i"]=> int(0) ["s"]=> int(0) ["f"]=> float(0) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(1) ["days"]=> int(11518) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) >Code language: PHP (php)

The DateInterval represents the differences between two dates in the year, month, day, hour, etc. To format the difference, you use the DateInterval ‘s format. For example:

 $dob = new DateTime('01/01/1990'); $to_date = new DateTime('07/15/2021'); echo $to_date->diff($dob)->format('%Y years, %m months, %d days');Code language: PHP (php)
31 years, 6 months, 14 daysCode language: PHP (php)

Adding an interval to a DateTime object

To add an interval to date, you create a new DateInterval object and pass it to the add() method. The following example adds 1 year 2 months to the date 01/01/2021 :

 $datetime = new DateTime('01/01/2021'); $datetime->add(new DateInterval('P1Y2M')); echo $datetime->format('m/d/Y');Code language: PHP (php)
03/01/2022Code language: PHP (php)

To format a date interval, you use the date interval format strings.

To subtract an interval from a DateTime object, you create a negative interval and use the add() method.

Summary

  • Use the DateTime class to work with the date and time.
  • Use the DateTimeZone class to work with time zones.
  • Use the comparison operators to compare two DateTime objects.
  • Use the diff() method to calculate the difference between to DateTime objects.
  • Use the DateInterval class to represent a date and time interval.
  • Use the add() method to add an interval to or subtract an interval from a DateTime object.

Источник

DateTime::setTime

Resets the current time of the DateTime object to a different time.

Parameters

Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

Return Values

Returns the DateTime object for method chaining or false on failure.

Changelog

Examples

Example #1 DateTime::setTime() example

 $date = new DateTime('2001-01-01'); $date->setTime(14, 55); echo $date->format('Y-m-d H:i:s') . "\n"; $date->setTime(14, 55, 24); echo $date->format('Y-m-d H:i:s') . "\n"; ?>
 $date = date_create('2001-01-01'); date_time_set($date, 14, 55); echo date_format($date, 'Y-m-d H:i:s') . "\n"; date_time_set($date, 14, 55, 24); echo date_format($date, 'Y-m-d H:i:s') . "\n"; ?>

The above examples will output something similar to:

2001-01-01 14:55:00 2001-01-01 14:55:24 

Example #2 Values exceeding ranges are added to their parent values

 $date = new DateTime('2001-01-01'); $date->setTime(14, 55, 24); echo $date->format('Y-m-d H:i:s') . "\n"; $date->setTime(14, 55, 65); echo $date->format('Y-m-d H:i:s') . "\n"; $date->setTime(14, 65, 24); echo $date->format('Y-m-d H:i:s') . "\n"; $date->setTime(25, 55, 24); echo $date->format('Y-m-d H:i:s') . "\n"; ?>

The above example will output:

2001-01-01 14:55:24 2001-01-01 14:56:05 2001-01-01 15:05:24 2001-01-02 01:55:24 

See Also

PHP 8.2

(PHP 5 5.2.0, 7, 8) DateTime::setDate date_date_set Sets the Object-oriented style Procedural style Resets the current date of DateTime object to different

(PHP 5 5.2.0, 7, 8) DateTime::setISODate date_isodate_set Sets the Object-oriented style Procedural style Set a date according to the ISO 8601 standard

(PHP 5 5.3.0, 7, 8) DateTime::setTimestamp date_timestamp_set Sets the and based on Unix Object-oriented style Procedural style Sets the date and time

(PHP 5 5.2.0, 7, 8) DateTime::setTimezone date_timezone_set Sets the for object Object-oriented style Procedural style Sets a new timezone for DateTime

Источник

Add hours to a date and time using PHP.

This is a tutorial on how to add hours to a date and time using PHP.

In this guide, we will provide examples using both the regular date and time functions, as well as PHP’s DateTime object.

Adding hours onto a date and time using PHP’s date and time functions.

Take a look at the following example, which is intentionally verbose:

//Get the current time in Unix. $currentTime = time(); //The amount of hours that you want to add. $hoursToAdd = 2; //Convert the hours into seconds. $secondsToAdd = $hoursToAdd * (60 * 60); //Add the seconds onto the current Unix timestamp. $newTime = $currentTime + $secondsToAdd; //Print it out in a format that suits you. echo date("d/m/y H:i", $newTime), '
'; //Or try this. echo "$hoursToAdd hour(s) added onto " . date("d/m/y H:i", $currentTime) . " becomes " . date("d/m/y H:i", $newTime);
  • Got the current Unix timestamp using PHP’s time function.
  • Defined a variable called $hoursToAdd, which contains the number of hours that we want to add onto our date and time. In this case, we will be adding 2 hours to the current time. If we wanted to add 12 hours to the current time, then we would simply change this variable to 12.
  • We then converted our hours into seconds by multiplying the number of hours by 3600 (60 x 60 = 3600). This works because there are 3600 seconds in one hour. In the case above, 2 is multiplied by 3600, which gives us 7200. This is correct, as there are 7200 seconds in two hours.
  • We then added these seconds onto the current timestamp.
  • Finally, we printed out the new date and time using PHP’s date function.

When I ran the code above, I received the following result:

2 hour(s) added onto 03/01/20 14:10 becomes 03/01/20 16:10

Adding hours onto a date and time using PHP’s DateTime object.

If you want to use the DateTime object for this operation, then you can use the following example:

//Get the current date and time. $current = new DateTime(); //The number of hours to add. $hoursToAdd = 2; //Add the hours by using the DateTime::add method in //conjunction with the DateInterval object. $current->add(new DateInterval("PTH")); //Format the new time into a more human-friendly format //and print it out. $newTime = $current->format('Y-m-d H:i'); echo $newTime;

As you can see, you do not need to do any multiplication sums while using the DateTime object, as it comes equipped with a handy method called DateTime::add.

In the code above, we simply passed a DateInterval object into this method. Our DateInterval object had PT2H set as the $interval_spec parameter, which basically translates into “a period of two hours.”

Other examples of what you could pass into the constructor of the DateInterval object:

  • PT1H: A period of one hour.
  • PT6H: A period of six hours.
  • PT24H: A period of 24 hours.

The most important thing in this case is that we use the letter “H” as the Period Designator.

Related tutorials:

Источник

Класс DateTime

DateTime::ATOM DATE_ATOM Atom (пример: 2005-08-15T15:52:01+00:00) DateTime::COOKIE DATE_COOKIE HTTP Cookies (пример: Monday, 15-Aug-2005 15:52:01 UTC) DateTime::ISO8601 DATE_ISO8601 ISO-8601 (пример: 2005-08-15T15:52:01+0000) DateTime::RFC822 DATE_RFC822 RFC 822 (пример: Mon, 15 Aug 05 15:52:01 +0000) DateTime::RFC850 DATE_RFC850 RFC 850 (пример: Monday, 15-Aug-05 15:52:01 UTC) DateTime::RFC1036 DATE_RFC1036 RFC 1036 (пример: Mon, 15 Aug 05 15:52:01 +0000) DateTime::RFC1123 DATE_RFC1123 RFC 1123 (пример: Mon, 15 Aug 2005 15:52:01 +0000) DateTime::RFC2822 DATE_RFC2822 RFC 2822 (пример: Mon, 15 Aug 2005 15:52:01 +0000) DateTime::RFC3339 DATE_RFC3339 Тоже, что и DATE_ATOM (начиная с версии PHP 5.1.3) DateTime::RSS DATE_RSS RSS (пример: Mon, 15 Aug 2005 15:52:01 +0000) DateTime::W3C DATE_W3C World Wide Web Consortium (пример: 2005-08-15T15:52:01+00:00)

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

Версия Описание
5.5.0 Класс теперь реализует DateTimeInterface.
5.4.24 Константа COOKIE изменена, чтобы соответствовать RFC 1036, где используются 4 цифры года вместо двух (RFC 850), как было в предыдущих версиях.
5.2.2 Результаты сравнения DateTime объектов при использовании операторов сравнения теперь соответствуют смыслу этих операторов. Ранее все объекты считались равными (==).

Источник

Читайте также:  Hello World
Оцените статью