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,276
  • 2
  • 32
  • 53
Muhammad Arif
  • 1,014
  • 3
  • 22
  • 56

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
  • 75,622
  • 18
  • 128
  • 150
  • 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
  • 33,050
  • 15
  • 95
  • 195
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
  • 148,279
  • 62
  • 259
  • 315
1

Try this

$date = new DateTime('01-04-2014');
echo $date->format('d,M H:i:s');
Dinesh
  • 4,066
  • 5
  • 21
  • 35
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
  • 4,069
  • 2
  • 29
  • 56