You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP:将硬编码带时区长日期转换为Y-m-d格式

PHP Date Conversion Without date() Function

Alright, let's tackle this problem. Since we can't rely on PHP's built-in date() function and our date is hardcoded, we can manually parse the string by breaking it into components and mapping month abbreviations to their numeric equivalents.

Here's a working implementation:

// Hardcoded original date string in the format: Weekday, Day Mon Year HH:MM:SS Timezone
$originalDate = "Fri, 23 Mar 2018 20:28:34 0000";

// Split the string into parts using spaces as delimiters
$dateSegments = explode(' ', $originalDate);

// Extract the day, month abbreviation, and year from the split array
$day = $dateSegments[1];
$monthShort = $dateSegments[2];
$year = $dateSegments[3];

// Create a mapping of 3-letter month abbreviations to two-digit numeric values
$monthMapping = [
    'Jan' => '01',
    'Feb' => '02',
    'Mar' => '03',
    'Apr' => '04',
    'May' => '05',
    'Jun' => '06',
    'Jul' => '07',
    'Aug' => '08',
    'Sep' => '09',
    'Oct' => '10',
    'Nov' => '11',
    'Dec' => '12'
];

// Get the two-digit month from our mapping
$month = $monthMapping[$monthShort];

// Construct the Y-m-d formatted date string
$formattedDate = "{$year}-{$month}-{$day}";

// Output will be: 2018-03-23
echo $formattedDate;

How this works:

  • We first split the original date string into an array using spaces, which lets us easily access the day, month abbreviation, and year components.
  • The $monthMapping array translates the 3-letter month code (like "Mar") into a two-digit number (like "03") to match the required Y-m-d format.
  • Finally, we concatenate the year, formatted month, and day into the desired string structure.

This approach is reliable as long as the input date string follows the exact format you specified—no need for any date parsing functions!

内容的提问来源于stack exchange,提问作者Jake S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:28:56