PHP code example of mducharme / date-formatter

1. Go to this page and download the library: Download mducharme/date-formatter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mducharme / date-formatter example snippets


$container = new \Pimple\Container();
$container->register(new \Mducharme\DateFormatter\ServiceProvider());


$formatter = $container['date/formatter'];
$displayDate = $formatter->format($date);

$formatter = new \Mducharme\DateFormatter\Formatter(
    new \Mducharme\DateFormatter\Parser()
);
$displayDate = $formatter->format($date);

use \Mducharme\DateFormatter\Parser;

$parser = new Parser();

// Setting the strict mode to false allows a parser that will not throw exceptions.
$softParser = new Parser(false);

// With proper parameters, the parser returns (parsed) Datetime objects
$parser->parse('now');

// With invalid string or types of parameter, the strict parser throws an `\InvalidArgumentException`.
$parser->parse('-invalid-');
$parser->parse(new InvalidObject());
$oarser->parse(false);

// By default, null is allowed. 
// Parsing returns null in this case, instead of the usual DateTimeInterface.
$parser->parse(null);

// If null is disallowed, attempting to parse a null value also throws an `\InvalidArgumentException`.
$parser->parse(null, false);


$parsed = $parser($date);

echo $formatter($date, 'atom');

$formatter = new Formatter($parser);
$allFormats = $formatter($date, Formatter::ALL);
var_dump($allFormats);

$customFormats = [
    'is-leap-year' => function(\DateTimeInterface $date) {
        return ($date->format('L') ? 'Yes' : 'No';
    },
    'custom-string' => 'H:i:S (u) d-m-Y'
];
$formatter = new Formatter($parser, $customFormats);

// Outputs "Yes" because 2012 was a leap year
echo $formatter(new DateTime('2012-01-01'), 'is-leap-year');

// Outputs the custom format
echo $formatter(new DateTime('2012-01-01'), 'custom-string');

$formats = $formatter('2012-01-01', ['atom', 'custom-string', 'is-leap-year']);

/**
 * @param \DateTimeInterface A date object.
 * @return string
 */
function callback(\DateTimeInterface $date);

// This will use the "atom" format as no default format was specified to the constructor
$formatter1 = new Formatter($parser, null, null);
echo $formatter1($date);

// This will use the "rfc822" format, as it was set as default
$formatter2 = new Formatter($parser, null, 'rfc822');
echo $formatter2($date);

$container = new \Pimple\Container();
$container->register(new \Mducharme\DateFormatter\ServiceProvider());

$parser = $container['date/parser'];
$formatter = $container['date/formatter'];