【问题标题】:How algorithm of strtotime(PHP Date function) Works?strtotime(PHP日期函数)的算法如何工作?
【发布时间】:2012-04-12 07:59:27
【问题描述】:
  1. 我想知道 strtotime(php 日期函数)是如何工作的?
  2. 如何将字符串“2012 年 9 月 15 日”解析为时间戳
  3. 有没有更好的算法?

我的目的是改变波斯语的这个功能

【问题讨论】:

标签: php algorithm date time persian


【解决方案1】:

您可以浏览 PHP 的源代码 (https://github.com/php/php-src) 并搜索功能以查看其实现。

更新

这里是函数strtotime()https://github.com/php/php-src/blob/master/ext/date/php_date.c#L1324的算法

问候!

【讨论】:

【解决方案2】:

因为 strtotime 接受英文输入,我建议使用波斯文输入: "15 (SOMETHING_PERSIAN) 2012" 并替换所需的字符串(我猜你需要一些 RegExp 和 switch 语句)并将其设为 "15 (SOMETHING_ENGLISH) 2012" 然后将其发送到 strtotime

【讨论】:

  • 问题是我想把“فروردین 12 2004”改成前 2004/6/12
  • 通过使用正则表达式,您将找到该字符串并将其替换为相应的英文等效项
  • 波斯语比较复杂....我更喜欢重写这个函数....
【解决方案3】:

我想知道 strtotime (php Date function) 是如何工作的?

去这里:https://github.com/php/php-src/blob/master/ext/date/lib/parse_date.c

搜索timelib_strtotime

【讨论】:

  • 源文件长达 25,000 行,显然是由类似 yacc/bison 的工具生成的。尽管它作为一个工作实现可能就足够了,但它作为任何学习如何实际完成的资源都没有用。
  • 我试图查看那个源代码,我觉得深渊在盯着我。
  • 有人可能更想查看github.com/php/php-src/blob/… - 那是用于生成 C 代码的文件。
【解决方案4】:

忘记它,使用 php Intl 扩展。未来将成为 php 核心的一部分。

<?php
    // format
    $format = datefmt_create('fa_IR@calendar=persian', IntlDateFormatter::FULL, IntlDateFormatter::FULL, 'Asia/Tehran', IntlDateFormatter::TRADITIONAL, 'yyyy/MM/dd HH:mm');

    // time in locale as you wish
    var_dump(datefmt_format($format, time())); // '۱۳۹۱/۰۲/۰۴ ۱۹:۱۵'

如果您想在 i18n 中支持所有语言的波斯语,请支持 ICU 项目。

php intl extension

icu-project.org

【讨论】:

    【解决方案5】:

    真正解析字符串的方法在parse_date.re's scan() method。在那里您会找到所有strtotime 关键字及其行为。

    该库包含在 https://github.com/derickr/timelib 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-23
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多