New datetime from string php

New datetime from string php

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?
Читайте также:  Curl custom headers php

Источник

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.

Источник

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