Date in a URL dd/mm/yyyy

前端 未结 1 445
孤独总比滥情好
孤独总比滥情好 2020-11-27 08:47

I am passing a date (dd/mm/yyyy) in URL with the following format:

http://www.website.com/_parameter=20/02/2000

I am using the following PHP to convert it to

相关标签:
1条回答
  • 2020-11-27 09:24

    When using strotime() you need to make sure you are using a valid datetime format. Otherwise strtotime() will return false or give you an unexpected value.

    Dates that use XX/XX/XXXX format are assumed to be in US format which means the first two digits represent the month, the next two digits represent the day of month, and the last four digits represent the year. When dashes are used, the dates are assumed to be in European format. For example:

    04/18/2017 = April 18, 2017
    12/18/2017 = December 18, 2017
    18-04-2017 = April 18, 2017
    18-12-2017 = December 18, 2017
    

    If you accidentally switch the day and month strtotime() will return false as the date is invalid.

    18/04/2017 // error
    18/12/2017 // error
    04-18-2018 // error
    12-18-2017 // error
    

    The above examples are straight forward. But you can run into issues when the dates can be ambigous. For example:

    04/12/2017 = April 12, 2017
    12/04/2017 = December 4, 2017
    04-12-2017 = December 4, 2017
    12-04-2017 = April 12, 2017
    

    In the above examples by switching the day and month we still get valid dates which can cause unexpected results in your application. To solve these potential issues it is recommended to use DateTime::createFromFormat() to parse the date ad return a DateTime() object from which you can get a Unix Timestamp, convert the date into another format, or use it to compare to other DateTime objects.

    // Parse US date format
    $date1 = DateTime::createFromFormat('m/d/Y', '04/18/2017');
    
    // Get Unix timestamp of 1493581268
    $timestamp = $date1->getTimestamp();
    
    // Parse European date format
    $date2 = DateTime::createFromFormat('d-m-Y', ''18-04-2017);
    
    // Get MySQL format (ISO-8601) of 2017-04-18
    $mysqlDate = $date2->format('Y-m-d');
    

    See also:

    • Compare DateTime objects with comparison operators in PHP

    For your specific case, the follow code will work:

    $date = $date1 = DateTime::createFromFormat('m/d/Y', '20/02/2000');
    $D->query = $date->format('Y-m-d'); // 2000-02-20
    
    0 讨论(0)
提交回复
热议问题