Home > OS >  Formatting date and time to pm/am. Php
Formatting date and time to pm/am. Php

Time:09-14

Could anyone suggest please. How to show time in pm/am format. I use such code. I formated dates/times according to the chosen locale.

$dt = DateTime::createFromFormat('Y-m-d H:i:s', $last_ticket['created_on']);

    $formatter = new IntlDateFormatter(
        Tickets::returnLocale(),
        IntlDateFormatter::FULL,
        IntlDateFormatter::SHORT,
    );
    return $formatter->format($dt);

It return Wednesday, 10 August 2022 at 21:42 but I need 10 August 2022 at 09:42 am

What appropriate pattern ? $formatter->setPattern('');

CodePudding user response:

Assuming $last_ticket['created_on'] is your date in the 'Y-m-d H:i:s' format (eg 2022-09-13 13:59:30), you need this:

$date = DateTime::createFromFormat('Y-m-d H:i:s', $last_ticket['created_on']);
return $date->format('d F Y \a\t h:i a');

Is should return something like "13 September 2022 at 01:59 pm".

As mentioned in the comments, check https://www.php.net/manual/en/datetime.format.php for more details.

edit

If you want to use the IntlDateFormatter you can do it like so:

$formatter = new IntlDateFormatter(
  Tickets::returnLocale(),
  IntlDateFormatter::FULL,
  IntlDateFormatter::SHORT,
  null,
  null,
  "d LLLL Y 'at' hh:mm a"
);
return $formatter->format($dt);

IntlDateFormatter is actually using a different syntax than DateTime::format, check here: https://unicode-org.github.io/icu/userguide/format_parse/datetime/

CodePudding user response:

When using the IntlDateFormatter you can either specify a fixed pattern according to the ICU documentation or try a combination of different date and time constants. If you use the constants, the format is different for almost every language.

$dt = date_create('2022-08-10 21:42');
$locale = 'en';
$formatter = new IntlDateFormatter(
        $locale,
        IntlDateFormatter::LONG,
        IntlDateFormatter::MEDIUM,
        null,
        null,
        //"d MMMM Y 'at' hh:mm a"
);
$date = $formatter->format($dt);
echo $date;

Result en: August 10, 2022 at 9:42:00 PM

Result it: 10 agosto 2022 21:42:00

To test an ICU format pattern, just uncomment it. Using a fixed pattern with at will look odd in non-enlish languages.

Example: 10 августа 2022 at 09:42 PM

Demo: https://3v4l.org/XvhQ5

  • Related