简体   繁体   English

如果字符串包含月份名称,则转换为数字

[英]If string contains month name then convert to number

I have a string $str that contains various date formats (I don't really have control of that!), is it possible to change any month names to numbers? 我有一个包含各种日期格式的字符串$str (我实际上没有控制权!),可以将任何月份的名称更改为数字吗?

These are some of the formats coming out: 这些是一些格式:

  • 2020-09-14 2020-09-14
  • 14-feb-2018 2018年2月14日
  • 14-march-2018 2018年3月14日

Would it then be possible to change all the date formats to the first example? 然后可以将所有日期格式更改为第一个示例吗?

Yah by this 是啊

$new_date = date('Y-m-d',strtotime($old_date));

Eg. 例如。

$new_date1 = date('Y-m-d',strtotime('14-feb-2018'));
$new_date2 = date('Y-m-d',strtotime('14-march-2018'));

Try this: 尝试这个:

function convertMonthToInt( $date ) {

    $date_bits = explode( "-", $date );

    $months = array(

        "january" => 1,

        //etc etc

    );

    if( is_string( $date_bits[ 1 ] ) !== true ) {

        return $date_bits[ 1 ];

    }

    return $months[ strtolower( $date_bits[ 1 ] ) ];

};

convertMonthToInt( "14-march-2018" );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM