Monty Shokeen Feb 26, 2021 Read Time: 12 mins url-selector#selectionChanged"> Deutsch English Español हिंदी Bahasa Indonesia Pусский You"ll often want to work with dates and times when developing websites, For example, you might need to show the last modified date on a post or mention how long ago a reader wrote some comment" /> Monty Shokeen Feb 26, 2021 Read Time: 12 mins url-selector#selectionChanged"> Deutsch English Español हिंदी Bahasa Indonesia Pусский You"ll often want to work with dates and times when developing websites, For example, you might need to show the last modified date on a post or mention how long ago a reader wrote some comment" />

Returns date formatted according to given format

post-promotion-placement#checkSidebarAdDisplayCondition" data-controller="scroll-position sticky-ad post-promotion-placement ">
*
Monty Shokeen Feb 26, 2021
Read Time: 12 mins url-selector#selectionChanged"> Deutsch English Español हिंदी Bahasa Indonesia Pусский

You"ll often want to work with dates and times when developing websites. For example, you might need lớn show the last modified date on a post or mention how long ago a reader wrote some comment. You might also have to show a countdown of the days until a special event.

Bạn đang xem: Returns date formatted according to given format

Luckily, PHP comes with some built-in date & time functions which will help us bởi all that và much more quite easily.

This tutorial will teach you how khổng lồ format the current date và time in PHP. You will also learn how khổng lồ get the timestamp from a date string and how to add and subtract different dates.

Getting the Date và Time in String Format

date($format, $timestamp) is one of the most commonly used date & time functions available in PHP. It takes the desired đầu ra format for the date as the first parameter & an integer as a timestamp value which needs to lớn be converted khổng lồ the given date format. The second parameter is optional, và omitting it will output the current date and time in string format based on the value of $format.

The $format parameter accepts a series of characters as valid values. Some of these characters have straightforward meanings: Y gives you the full numeric representation of the year with 4 digits (2018), and y only gives you the last two digits of the current year (18). Similarly, H will give you the hour in 24-hour format with leading zeros, but h will give you the hour in 12-hour format with leading zeros.

Here are some of the most common date format characters & their values.

CharacterMeaningExample
dday of the month with leading zeros03 or 17
jday of the month without leading zeros3 or 17
Dday of the week as a three-letter abbreviationMon
lfull day of the weekMonday
mmonth as a number with leading zeros09 or 12
nmonth as a number without leading zeros9 or 12
Mmonth as a three-letter abbreviationSep
Ffull monthSeptember
ytwo-digit year18
Yfull year2018

There are many other special characters khổng lồ specify the output for the date() function. It is best lớn consult the format characters table in the date() function documentation for more information about special cases.

Let"s see some practical examples of the date() function now. We can use it lớn get the current year, current month, current hour, etc., or we can use it to get a complete date string.

You can also use the date() function to đầu ra the time. Here are some of the most commonly used time format characters:

CharacterMeaningExample
ghours in 12-hour format without leading zeros1 or 12
hhours in 12-hour format with leading zeros01 or 12
Ghours in 24-hour format without leading zeros1 or 13
Hhours in 24-hour format with leading zeros01 or 13
aam/pm in lowercaseam
Aam/pm in uppercaseAM
iminutes with leading zeros09 or 15
sseconds with leading zeros05 or 30

And here are some examples of outputting formatted time strings.

// output — 11:03:37 AMecho date("h:i:s A");// output đầu ra — Thursday, 11:04:09 AMecho date("l, h:i:s A");// output đầu ra — 13 September 2018, 11:05:00 AMecho date("d F Y, h:i:s A");?>It is also important that you escape these special characters if you want lớn use them inside your date string.

Get the Unix Timestamp

Sometimes, you will need lớn get the value of the current Unix timestamp in PHP. This is very easy with the help of the time() function. It returns an integer value which describes the number of milliseconds that have passed since 1 January 1970 at midnight (00:00:00) GMT.

You can also use this function to lớn go back và forth in time. To vì so, all you have to bởi is subtract the right number of seconds from the current value of time() and then change the resulting value into the desired date string. Here are two examples:

One important thing you should remember is that the timestamp value returned by time() is time-zone agnostic and gets the number of seconds since 1 January 1970 at 00:00:00 UTC. This means that at a particular point in time, this function will return the same value in the US, Europe, India, or Japan.

Another way khổng lồ get the timestamp for a particular date would be to use the mktime($hour, $minute, $second, $month, $day, $year) function. When all the parameters are omitted, this function just uses the current local date and time lớn calculate the timestamp value. This function can also be used with date() to generate useful date và time strings.

Basically, time() can be used to go back and forth khổng lồ a period of time, while mktime() is useful when you want to go khổng lồ a particular point in time.

Convert a Datetime String to lớn a Timestamp

The strtotime($time, <$now = time()>) function will be incredibly helpful when you want to convert different date và time values in string format to lớn a timestamp. The function can parse almost all kinds of datetime strings into timestamps.

You should definitely check the valid time formats, date formats, compound datetime formats, and relative datetime formats.

With relative datetime formats, this function can easily convert commonly used strings into valid timestamp values. The following examples should make it clear:

Adding, Subtracting, and Comparing Dates

It"s possible to add and subtract specific periods of time to and from a date. This can be done with the help of the date_add() and date_sub() functions. You can also use the date_diff() function khổng lồ subtract two dates and output the difference between them in terms of years, months, and days, or something else.

Generally, it"s easier to vày any such date and time related arithmetic in object-oriented style with the DateTime class instead of doing it procedurally. We"ll try both these styles here, & you can choose whichever you like the most.

format("%Y years, %M months and %d days");$present = new DateTime("now");$future = new DateTime("last day of January 2024");$interval = $present->diff($future);// đầu ra — 05 years, 04 months & 17 daysecho $interval->format("%Y years, %M months & %d days");?>When using DateTime::diff(), the DateTime object on which the diff() method is called is subtracted from the DateTime object which is passed to lớn the diff() method. When you are writing procedural style obatambeienwasirherbal.com, the first date parameter is subtracted from the second date parameter.

Xem thêm: Chung Kết Liên Minh Huyền Thoại 2018, Chung Kết Thế Giới Liên Minh Huyền Thoại

Both the function và the method return a DateInterval() object representing the difference between two dates. This interval can be formatted to give a specific output using all the characters listed in the format() method documentation.

The difference between object-oriented style & procedural style becomes more obvious when subtracting or adding a time interval.

You can instantiate a new DateTime object using the DateTime() constructor. Similarly, you can instantiate a DateInterval object using the DateInterval() constructor. It accepts a string as its parameter. The interval string starts with P, which signifies period. After that, you can specify each period using an integer value and the character assigned to a particular period. You should kiểm tra the DateInterval documentation for more details.

Here is an example that illustrates how easy it is to showroom or subtract dates & times in PHP.

add($the_interval);// đầu ra — It will be Saturday, 05 March, 2039 after trăng tròn years, 05 months và 20 days from today.echo "It will be ".$now->format("l, d F, Y")." after ".$the_interval->format("%Y years, %M months and %d days")." from today.";$now = date_create("now");$the_interval = date_interval_create_from_date_string("20 years 05 months đôi mươi days");date_add($now, $the_interval);// output — It will be Saturday, 05 March, 2039 after 20 years, 05 months and 20 days from today.echo "It will be ".$now->format("l, d F, Y")." after ".$the_interval->format("%Y years, %M months & %d days")." from today.";?>You can also compare dates in PHP using comparison operators. This can come in handy every now & then. Let"s create a Christmas day counter using the comparison operators và other DateTime methods.

$christmas) $christmas->add(new DateInterval("P1Y"));if($now diff($christmas); echo $interval->format("%a days")." until Christmas!";}if($now == $christmas) echo "Merry Christmas :)";// đầu ra — 103 days until Christmas!?>We began by creating two DateTime objects lớn store the present time and the date of this year"s Christmas. After that, we run a while loop khổng lồ keep adding 1 year to the Christmas date of 2018 until the present date is less than the Christmas date. This will be helpful when the obatambeienwasirherbal.com runs on 18 January 2024. The while loop will increment the Christmas date as long as it is less than the present date at the time of running this script.

Our Christmas day counter will now work for decades to lớn come without any problems.

Frequently Asked Questions About date() in PHP

There are some common questions about getting different kinds of information from the date() function in PHP that pop up every now & then. We will try to lớn answer all of them here.

How bởi vì I Get the Current Year in PHP?

You can get the current year in PHP by using date("y") or date("Y"). Using a capital Y will give you all the digits of the current year, lượt thích 2021. Using the small y will only give you the last two digits, lượt thích 21.

What Is the Right Way lớn Get the Current Month in PHP?

There are four different characters for getting the current month in PHP, depending on the format you want. You can use the capital letter F khổng lồ get the full name of the month, like February, or get the month in a shorter three-letter format by using M.

You can also get the current month in numerical terms by using m and n, which will give you the month with và without leading zeroes respectively.

How Can I Get the Day of the Week in PHP?

You can also get the day of the week in PHP by using four different characters. The capital D will give you a three-letter representation of the day of the week, like Mon or Tue. Using an l (lowercase L) will give you the full name of the day of the week.

You can get a numerical value between 0 (for Sunday) and 6 (for Saturday) for the days of a week by using w.

How bởi I Get the Current Time in 12-Hour Format in PHP?

You can get the current time of the day in a 12-hour format by using g or h. With g, you will get the time without any leading zeroes, while h will add some leading zeroes. The AM or PM can be added by using a (for small letters) or A (for capital letters).

Can I Get the Current Time in 24-Hour Format in PHP?

Using the characters G and H will give you the current hour of the day in 24-hour format. You won"t get any leading zeroes with G, but H will showroom leading zeroes.

What Is the Best Way lớn Escape Characters in a Date Format?

The date() function accepts a string as its parameter, but many characters have a well-defined meaning, lượt thích Y for year and F for a month. This means that using these characters directly as part of a string may not always have the desired results.

If you want the date() function to đầu ra these characters, then you have to lớn escape them first. Here is an example:

Some of the characters, like t, need two backslashes because  is meant for tabs. If possible, it is advisable khổng lồ just put the regular string that you want lớn echo outside date(). Otherwise, you will be escaping a lot of characters.

Final Thoughts

In this tutorial, we learned how to output đầu ra the current date and time in a desired format using the date() function. We also saw that date() can also be used to get only the current year, month, & so on. After that, we learned how to lớn get the current timestamp or convert a valid DateTime string into a timestamp. Finally, we learned how to địa chỉ cửa hàng or subtract a period of time from different dates.

I"ve tried to lớn cover the key DateTime functions & methods here. You should definitely take a look at the documentation to read about the functions not covered in the tutorial. If you have any questions, feel miễn phí to let me know in the comments.