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

PHP:如何将文本日期字符串转换为2022-10-13格式的有效日期

日期字符串转换:Thu, Oct 13, 2022 → 2022-10-13

以下是几种主流编程语言的简便实现方案:

Python

利用标准库datetime的解析和格式化方法,一步到位:

from datetime import datetime

raw_date = "Thu, Oct 13, 2022"
target_date = datetime.strptime(raw_date, "%a, %b %d, %Y").strftime("%Y-%m-%d")
print(target_date)  # 输出:2022-10-13
  • %a匹配星期缩写(如Thu),%b匹配月份缩写(如Oct),%d是两位日期,%Y是4位年份,解析后直接转成yyyy-MM-dd格式。

JavaScript

两种常用方式,按需选择:

方式1:借助Intl API快速格式化

const rawDate = "Thu, Oct 13, 2022";
const date = new Date(rawDate);
const targetDate = new Intl.DateTimeFormat('en-CA').format(date);
console.log(targetDate);  // 输出:2022-10-13

方式2:手动拼接(兼容性更强)

const rawDate = "Thu, Oct 13, 2022";
const date = new Date(rawDate);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const targetDate = `${year}-${month}-${day}`;
console.log(targetDate);  // 输出:2022-10-13

Java(Java 8+)

使用java.time包的DateTimeFormatter处理,线程安全且更灵活:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateConvertDemo {
    public static void main(String[] args) {
        String rawDate = "Thu, Oct 13, 2022";
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("EEE, MMM dd, yyyy", Locale.ENGLISH);
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        
        LocalDate date = LocalDate.parse(rawDate, inputFormatter);
        String targetDate = date.format(outputFormatter);
        
        System.out.println(targetDate);  // 输出:2022-10-13
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:01:09