How to change php date format?

Most of the countries are using different date format. There is a large variety of date formats in use, which differ in the order of date components, component separators, whether leading zeros are included, whether all four digits of the year are written, and whether the month is represented numerically or by name.

The basic components of a calendar date for the most common calendar systems is represented as Y – Year, M – Month and D – Day

The above 3 components can be ordered as

B – Big-endian (year, month, day), e.g. 1996-04-22

L – Little-endian (day, month, year), e.g. 22.04.96 or 22/04/96 or 22 April 1996

M – Middle-endian (month, day, year), e.g. 04/22/96 or April 22, 1996

Some Specific formats followed for the above basic components:

yy – Two-digit year, e.g. 96

yyyy – Four-digit year, e.g. 1996

m – One-digit month for months below 10, e.g. 4

mm – Two-digit month, e.g. 04

mmm – Three-letter abbreviation for month, e.g. Apr

mmmm – Month spelled out in full, e.g. April

d – One-digit day for days below 10, e.g. 2

dd – Two-digit day, e.g. 02

Separators of the components:

/” – Slash

.” – Dots or full stops

” – Hyphens or dashes

” ” – Spaces

PHP provides many date formats. See the list of Date Formats.

Previously, we have learnt how to format the date and time using PHP date() function from here. Now, we are going to learn about how to change the date in different format using php. PHP strtotime() function achieve this.

strtotime ()

This function is to generate date in user required format. It converts the input date string to time format.

Syntax

date(”, strtotime(<$date>))

str_replace()

The function used to replace the symbol between the Date/Month/Year

Syntax

str_replace(‘-‘,’/’,<$date>)

Let see the sample program for the date function

<?php
$date=date("m-d-Y");

function dateFromString($date) 		//function for modify the date format
{
return date('Y-m-d', strtotime( str_replace('-','/',$date)));
}

echo dateFromString($date);

?>

After converting the date and time into specific format, we can now insert the value into mysql table.

About

Smart Guy/ PHP Developer

Posted in Php Tagged with: , ,