CONVERSION OF A STRING TO THE DESIRED DATE FORMAT USING PHP

  1. Strtotime:

Strtotime function will be helpful only if the string is in the following format.

$date=”31-01-2016″; // Assuming  the string to be Jan 31, 2016

date(“Y-M-d”, strtotime ($date));

Result: 2016-Jan-31

$date=”01-31-2016″; // Assuming  the string to be Jan 31, 2016

date(“Y-M-d”, strtotime ($date));

Result: 1970-Jan-01

Strtotime fails to help in this scenario.

2. Mktime:

Using mktime, we can achieve the desired format as follows:

Syntax: $time=mktime(hour,minute,second,month,day,year,is_ds);

Example:

$time=mktime(0,0,0,01,31,2016,0);

date(‘Y-M-d’,$time);

Result: 2016-Jan-31

However, you cannot explode the string and pass the values in the corresponding places as it lengthens coding and execution time.

3. DateTime::createFromFormat

$date1=”01-31-2016”;

$date = DateTime::createFromFormat(‘m-d-Y’, $date1);// I am assuming that my string is in m-d-Y format

$date->format(‘Y-m-d’); 

Result: 2016-Jan-31

If my string is in d-m-Y format:

$date = DateTime::createFromFormat(‘d-m-Y’, $date1);// I am assuming that my string is in m-d-Y format

$date->format(‘Y-m-d’); 

Result: 2016-Jan-31

Unlike strtotime, the above helps in all scenarios and thus proves effective.

Advertisements
Posted in PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s