简体   繁体   中英

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?

These are some of the formats coming out:

  • 2020-09-14
  • 14-feb-2018
  • 14-march-2018

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" );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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