1

I have date list. I want 01-04-2014 show as Jan 4 and 01-05-2014 show as Jan 5. How do i do this? Here is my code:

$dates = array();
$timestamp = strtotime('-30 days');
for ($i = 0 ; $i <=30 ; $i++) {

    //insert the date
    $dates[$i]= date('m-d-Y', $timestamp);

    //increase the day
    $timestamp += 24 * 3600;
}

First i want to get dates then convert after for loop.

dersvenhesse
  • 6,015
  • 2
  • 28
  • 50
Arsal Ali
  • 978
  • 3
  • 20
  • 54

5 Answers5

5

Use DateTime objects:

$str = '01-04-2014';
$dateObj = DateTime::createFromFormat('m-d-Y', $str);
echo $dateObj->format('M d');

Output:

Jan 04

Explanation:

For a list of other available formatting options, see the documentation for date().

Amal Murali
  • 73,160
  • 18
  • 123
  • 143
  • Note: `DateTime::createFromFormat()` will not work in php<5.2.1 – krishna Feb 03 '14 at 12:35
  • Note: True. Although: anything before PHP 5.3.0 is *ancient*. You should **upgrade** to a modern PHP version. Also, the DateTime class has some really cool features and works on a wider range of dates (that strtotime() and date() can't handle on 32-bit systems). – Amal Murali Feb 03 '14 at 12:39
  • I just left the note for helping purpose.I accept your point too. – krishna Feb 03 '14 at 12:43
2

date can do that all for you:

echo date("M j", $timestamp);

It has many more formatting options.

Bart Friederichs
  • 32,037
  • 14
  • 96
  • 185
2

Try with:

$dates = array();
$timestamp = strtotime('-30 days');
for ($i = 0 ; $i <=30 ; $i++) {
   $dates[$i]= date('M j', $timestamp);
   $timestamp += 24 * 3600;
}
hsz
  • 143,040
  • 58
  • 252
  • 308
1

Try this

$date = new DateTime('01-04-2014');
echo $date->format('d,M H:i:s');
Dinesh
  • 3,886
  • 4
  • 20
  • 33
0

try this.It works in all PHP versions

$input = '01-04-2014';
$a = explode('-',$input);
$result = strftime("%b",mktime(0,0,0,$a[0])).''.intval($a[1]); 
echo $result;

Demo

krishna
  • 3,996
  • 2
  • 27
  • 56