How to format a date in PHP?

by cortez.connelly , in category: PHP General , a year ago

How to format a date in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by denis , a year ago

@cortez.connelly 

In PHP, the date() function is used to format a date and time string according to a specified format. The function takes two arguments: the format string and an optional timestamp value.


Here's an example of how to format a date using the date() function in PHP:

1
$date = date('Y-m-d'); // returns the current date in the format of year-month-day (e.g. 2023-03-30)


In this example, the 'Y-m-d' format string specifies that the date should be formatted with the year, month, and day separated by hyphens.


Here are some of the most commonly used format characters in the date() function:

  • Y - 4 digit year
  • m - month with leading zeros (01-12)
  • d - day of the month with leading zeros (01-31)
  • H - 24-hour format of an hour with leading zeros (00-23)
  • i - minutes with leading zeros (00-59)
  • s - seconds with leading zeros (00-59)


You can use these format characters in any combination to create a custom date format string that suits your needs.

by arnoldo.moen , 10 months ago

@cortez.connelly 

In PHP, you can format a date using the date() function. The date() function accepts two arguments: a format string and a timestamp. The timestamp is an optional argument that specifies the Unix timestamp for the date you want to format. If you don't specify a timestamp, the date() function will use the current date and time.


Here's an example of how to format the current date and time using the date() function:

1
2
3
<?php
echo date("Y-m-d H:i:s");
?>


This will output the current date and time in the format "YYYY-MM-DD HH:MM:SS".


Here's a breakdown of the format string:

  • Y: Four-digit year
  • m: Two-digit month (with leading zeros)
  • d: Two-digit day of the month (with leading zeros)
  • H: Two-digit hour in 24-hour format (with leading zeros)
  • i: Two-digit minute (with leading zeros)
  • s: Two-digit second (with leading zeros)


You can customize the format string to display the date and time in different formats. For example, if you wanted to display the date in the format "Day, Month DD, YYYY", you could use the following format string:

1
2
3
<?php
echo date("l, F j, Y");
?>


This will output the current date in the format "Day, Month DD, YYYY" (e.g., "Sunday, April 11, 2023").