Magnar Myrtveit
Magnar Myrtveit

Reputation: 2740

Removing time part in IntlDateFormatter

I would like to output a localized date and have tried this:

$time = new DateTime();
echo IntlDateFormatter::formatObject($time)."\n";
echo IntlDateFormatter::formatObject($time, [IntlDateFormatter::NONE, IntlDateFormatter::MEDIUM])."\n";
echo IntlDateFormatter::formatObject($time, [IntlDateFormatter::MEDIUM, IntlDateFormatter::NONE])."\n";

I get this output:

Oct 28, 2015, 2:10:50 PM
2:10:50 PM
20151028 02:10 PM

So removing the datepart works fine, but not removing the time part. What am I doing wrong?

You can try it out here: https://3v4l.org/UdtoX

Edit:

The reason I want to use IntlDateFormatter is to get i18n of the date. For example, I should get different results if I set Locale::setDefault('en_GB') and if I set Locale::setDefault('no_NO') before using IntlDateFormatter. Therefore I don't want to specify the format manually.

Upvotes: 1

Views: 1486

Answers (2)

Magnar Myrtveit
Magnar Myrtveit

Reputation: 2740

It seems to be a bug in PHP. By creating an object instead of calling the static method it works :)

$formatter = new IntlDateFormatter(Locale::getDefault(), IntlDateFormatter::MEDIUM, IntlDateFormatter::NONE);
echo $formatter->format($time);

Gives the desired output Oct 28, 2015.

Upvotes: 3

Fluinc
Fluinc

Reputation: 491

<?php
$date = new DateTime();

$dateFormatter = IntlDateFormatter::create(
  Locale::getDefault(),
  IntlDateFormatter::NONE,
  IntlDateFormatter::NONE,
  date_default_timezone_get(),
  IntlDateFormatter::GREGORIAN,
  'MM/dd/yyyy'
);

var_dump($dateFormatter->format($date));

Upvotes: 0

Related Questions