Locale-formatted strftime using IntlDateFormatter

Overview

GitHub license GitHub release Packagist Packagist Downloads GitHub issues GitHub forks GitHub stars

strftime

Locale-formatted strftime using IntlDateFormatter (PHP 8.1 compatible)

This provides a cross-platform alternative to strftime() for when it will be removed from PHP.

Note that output can be slightly different between libc sprintf and this function as it is using ICU.

Original code: https://gist.github.com/bohwaz/42fc223031e2b2dd2585aab159a20f30

Original autor: BohwaZ

Requirements

Installation

Composer install

You can install this plugin into your application using composer:

  • Add php81_bc/strftime package to your project:

      composer require php81_bc/strftime
  • Load the function PHP81_BC\strftime in your project

    
      require 'vendor/autoload.php';
      use function PHP81_BC\strftime;

Manual install

  • Download php-8.1-strftime.php and save it to an accessible path of your project.
  • Load the function PHP81_BC\strftime in your project
    
      require 'php-8.1-strftime.php';
      use function PHP81_BC\strftime;

Usage

  use function PHP81_BC\strftime;
  echo strftime('%A %e %B %Y %X', new \DateTime('2021-09-28 00:00:00'), 'fr_FR');

Original use

  \setlocale(LC_TIME, 'fr_FR.UTF-8');
  echo \strftime('%A %e %B %Y %X', strtotime('2021-09-28 00:00:00'));
Comments
  • doesn't work with LC_TIME=nb_NO.UTF8 ?

    doesn't work with LC_TIME=nb_NO.UTF8 ?

    my LC_TIME is "nb_NO.UTF8", and $format is "%A %d. %B" and $timestamp is 1655935200 and strftime() gives me "torsdag 23. juni", but \PHP81_BC\strftime gives me "Thursday 23. June"

    .. any idea what went wrong here? reproduce script:

    <?php
    require_once('vendor/autoload.php');
    if(false === setlocale(LC_TIME, "nb_NO.UTF8")){
     die("error: locale nb_NO.UTF8 is not installed");
    }
    $stamp = 1655935200;
    $format = "%A %d. %B";
    var_dump(\PHP81_BC\strftime($format, $stamp));
    var_dump(strftime($format, $stamp));
    

    outputs on my system (PHP7.4.29):

    root@75cee9b6f638:/var/www# php test.php
    string(17) "Thursday 23. June"
    string(16) "torsdag 23. juni"
    

    what went wrong here?

    opened by divinity76 13
  • Fallback when intl is missing

    Fallback when intl is missing

    This implements a mechanism to replace the locale aware part of the function with differrent formatter classes.

    For now it simply implements a fallback to a non-locale aware formatting using DateTime->format() when the intl extension is missing. Future extension could implement making use of strftime() if it still exist or implement locale formatting in pure PHP.

    For testing a environment variable STRFTIME_NO_INTL can be set to force using the fallback.

    Currently the test for the gregorian calendar jump fails, but I don't understand the issue well enough to fix it.

    enhancement 
    opened by splitbrain 4
  • PSR-12 compability?

    PSR-12 compability?

    I noticed the code is currently using a somewhat uncommon formatting (partly enforced via editor config). Would it make sense to adopt PSR-12? I'm happy to provide a pull request if wanted.

    opened by splitbrain 2
  • Minimum PHP version in composer.json is incorrect

    Minimum PHP version in composer.json is incorrect

    Currently, the composer.json lists a minimum PHP version of 5.6, but the actual code includes many features which require later versions, such as a type declaration of ?string, which is only valid since PHP 7.1

    Either the documented minimum version should be updated, or the code changed to run on older versions.

    opened by IMSoP 2
  • Account for different handling of historical dates by ICU and Posix

    Account for different handling of historical dates by ICU and Posix

    The Gregorian calendar was introduced in much of Europe in October 1582, with 4th October followed by the 15th October. ICU interprets historical dates based on this transition by default, but Posix and timelib do not.

    opened by IMSoP 1
  • Try to use LC_TIME locale if locale param is empty

    Try to use LC_TIME locale if locale param is empty

    Using LC_TIME locale if possible will make the function more compatible to the current behaviour.

    The Locale class also supports identifiers with dashes and may be more than 5 characters; see https://www.php.net/manual/en/class.locale.php

    opened by the-mars 1
  • Add support for modifiers to remove leading zeros or convert to spaces

    Add support for modifiers to remove leading zeros or convert to spaces

    The buildin strftime currently supports modifiers after the % sign. They are not documented at php.net/manual/en/function.strftime but they work on Linux and I have seen code which is using it.

    For example %-d will remove a leading zero if the day of month <10. While %_d will replace the leading zero by a space. I found in a comment that on Windows %#d is doing the same as %-d, so I added it too. This will make it platform-independent ;-)

    opened by the-mars 1
  • Removed never reachable if statement

    Removed never reachable if statement

    The class type check will never return false, as DateTime is always an instance of DateTimeInterface. If the passed $timestamp is invalid, then the DateTime constructor will throw an \Exception, therefore the check is not needed.

    opened by TiberiuD 0
  • "Stand-alone" versions of "month in year" and "day of week" formats more closely mimic strftime in German locale

    Currently this library uses EEE and MMM for %a and %b. However I noticed with my own project's test suite that in the German locale that the "stand-alone" formats ccc and LLL more closely mimic what strftime does for %a and %b.

    In particular EEE and MMM formats do not always truncate to 3 characters in the German locale (they sometimes generate 2 or 4 characters). They also add a period . after the truncated part which strftime does not do.

    Switching to ccc and LLL has no effect on the English and Spanish locales in my test suite.

    Looking at what "stand-alone" is for (https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetime-format-syntax) I think it is more correct to use the stand-alone formats in a strftime polyfill. While using EEE and MMM would potentially improve the output grammar when the format string combines multiple date parts, you'd have to look at the format string as a whole to know if you need to use the stand-alone versions or not. And at least my libc's strftime does not do this.

    opened by arkonan 1
  • Behaves differently from stock `strftime` for the Italian default year format

    Behaves differently from stock `strftime` for the Italian default year format

    Hi, it seems that \PHP81_BC\strftime behaves differently from stock strftime for the Italian default year format

    <?php
    require_once "vendor/autoload.php";
    
    $dt = new \DateTime("2022-01-01 00:00:00");
    
    setlocale(LC_TIME, 'it_IT.utf8');
    var_dump(strftime("%x %X", $dt->getTimestamp()));
    var_dump(\PHP81_BC\strftime("%x %X", $dt->getTimestamp()));
    

    outputs

    string(19) "01/01/2022 00:00:00"
    string(17) "01/01/22 00:00:00"
    
    opened by nu111 14
Releases(0.5.0)
Owner
Fernando Herrero
Programar es una pasión, resolver problemas un pasatiempo, superarse una meta.
Fernando Herrero
This library helps PHP users to convert and using Jalali DateTime format

Easy Jalali for PHP V1.0.0 Jalali calendar converter for Persian users in Iran, Afghanistan and other countries that use Jalali calendar. Very thanks

Majid J 3 Mar 20, 2022
Automatically updated tree-formatted database from MaxMind database

Geo IP Database This is an automated repository that downloads and processes GeoLite database from Maxmind GeoLite database, and processes it to be co

Ayesh Karunaratne 7 Nov 22, 2022
Polish locale package for Magento 2

Polski pakiet językowy dla Magento 2 Repozytorium zawiera gotowy komponent z językiem polskim dla Magento 2. Tłumaczenia są synchronizowane ze zmianam

SNOW.DOG 17 Dec 22, 2020
Faker-driven, configuration-based, platform-agnostic, locale-compatible data faker tool

Masquerade Faker-driven, platform-agnostic, locale-compatible data faker tool Point Masquerade to a database, give it a rule-set defined in YAML and M

elgentos ecommerce solutions 219 Dec 13, 2022
A module allowing you to write your Processwire template using MJML and get a converted HTML output using MJML API.

PageMjmlToHtml A module allowing you to write your Processwire template using MJML and get a converted HTML output using MJML API. This is considered

Romain Cazier 7 Oct 5, 2022
This repository demonstrates exemplary implementation of chat using HTTP and Websocket servers in PHP using Kraken Framework components.

This repository demonstrates exemplary implementation of chat using HTTP and Websocket servers in PHP using Kraken Framework components.

Kraken 48 Aug 11, 2021
A research raw data repository for researchers of Arba Minch University built using Codeigniter which follows MVC architecture. The front-end is build using Bootstrap.

Arba Minch University Dataset Repository This system is a research dataset repository for Arba Minch University researchers and is build using Codeign

Wuletaw Wonte 8 Jul 1, 2022
Backend application using Laravel 9.x REST APIs for games topup from digiflazz.com and payment gateway using xendit.co

TOPUP - Laravel 9.x REST API Documentation is still on progress. For now, you can fork this postman collection Installation Clone this project git clo

Muhammad Athhar Kautsar 46 Dec 17, 2022
This PHP library will help you to work with your Pinterest account without using any API account credentials.

Pinterest Bot for PHP A PHP library to help you work with your Pinterest account without API credentials. The Pinterest API is painful: receiving an a

Sergey Zhuk 414 Nov 21, 2022
Iteration primitives using generators

Iteration primitives using generators This library implements iteration primitives like map() and filter() using generators. To a large part this serv

Nikita Popov 1.1k Dec 31, 2022
Cache slam defense using a semaphore to prevent dogpile effect.

metaphore PHP cache slam defense using a semaphore to prevent dogpile effect (aka clobbering updates, stampending herd or Slashdot effect). Problem: t

Przemek Sobstel 102 Sep 28, 2022
A static php code analysis tool using the Graph Theory

Mondrian Ok guyz, you have a master degree in Graph Theory, you follow Law of Demeter and you live on S.O.L.I.D principles ? Let's have some Fun ! (^ω

Florent Genette 391 Nov 30, 2022
Lovely PHP wrapper for using the command-line

ShellWrap What is it? It's a beautiful way to use powerful Linux/Unix tools in PHP. Easily and logically pipe commands together, capture errors as PHP

James Hall 745 Dec 30, 2022
[READ-ONLY] A flexible, lightweight and powerful Object-Relational Mapper for PHP, implemented using the DataMapper pattern. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP ORM The CakePHP ORM provides a powerful and flexible way to work with relational databases. Using a datamapper pattern the ORM allows you to m

CakePHP 146 Sep 28, 2022
Simple composer script to manage phar files using project composer.json.

tooly-composer-script With tooly composer-script you can version needed PHAR files in your project's composer.json without adding them directly to a V

Tommy Mühle 100 Sep 27, 2022
Documentation generator for PHP Code using standard technology (SRC, DOCBLOCK, XML and XSLT)

phpDox phpDox is a documentation generator for PHP projects. This includes, but is not limited to, API documentation. The main focus is on enriching t

Arne Blankerts 588 Dec 22, 2022
Value Object that represents a monetary value (using a currency's smallest unit).

This project has been abandoned. It was only ever intended to be used as an example for PHPUnit features etc. and not for usage in production. I am so

Sebastian Bergmann 735 Dec 30, 2022
Send email across all platforms using one interface

Send email across all platforms using one interface. Table Of Content Requirements Installation Providers AmazonSES Mailgun Mailjet Mandrill Postmark

Omnimail 329 Dec 30, 2022