There is some point in time when we need to add a number of days, months, years, hours, minutes and seconds to Date and time. PHP serves us with several built-in functions to do this. Some built-in functions that we will discuss here are date_create(), date_format() and date_add().
This function is used to create a DateTime object by using a date/time string and timezone. The default value of the date/time string is current date/time.
DateTime date_create(time, timezone);
Parameters:This function accepts two parameters:
- time : (optional) Specifies a date/time string. NULL or default value
indicates the current date/time. You may refer to this link for supported date and time formats in PHP.
- timezone : (optional) Time zone of the time.
Return Value: This function returns a new DateTime object which specifies a date.
The date_format() function formats a given date. The date is supplied as DateTime instance which is generally returned by the date_create() function and format is a string according to which we want to format the date.
string date_format(object, format);
Parameters : This function accepts two parameters, all of this which are mandatory to be supplied.
- object : Specifies a DateTime object returned by date_create()
- format : Specifies the format for the date. It accepts the formats that is supported by date() function in PHP. Example – H(24-hr Format), h(12-hr Format), i(minutes:00 to 59), s(seconds: 00 to 59) etc.
Return Value: The date_format() function returns a string which represents the date formatted according to the specified format on successful formatting otherwise it returns false on faliure.
The date_add() function is used to add days, months, years, hours, minutes and seconds to a Date. The Date is supplied as a DateTime object to the date_add() function and the interval which we want to add to our Date is supplied as a DateInterval object.
DateTime date_add(object, interval);
Parameters:This function accepts three parameters, all of this which are mandatory to be supplied.
- Object : Specifies a DateTime object returned by date_create(). This function returns a new DateTime object.
- Interval : Specifies a DateInterval object i.e it stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTime’s constructor supports.
Return Value : This function returns a DateTime object on success else FALSE on failure.
Below programs illustrate the date_add() function in PHP:
Note : Using ‘+’ operator we can add more to date and time.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.