创建格式未知的日期/时间 [英] Create date/time when the format is unknown

查看:94
本文介绍了创建格式未知的日期/时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个小型应用程序,它从不同的站点导入几个CSV文件。每个网站都有自己的日期格式。一些格式如下。

I am working on a small application which imports several CSV files from different sites. Each site have their own format for date. Some of the formats are below.

  '2013-12-04 11:32:21 +0000'
  '04/12/2014 +0000'
  '04/12/2014 +0000 11:32:21'
  'Fri Mar 14 18:19:26 +0000 2014'

我需要将以上格式转换为简单格式,如'd-m'Y'。这里的问题是,格式不是提前知道的,每次新的CSV文件需要添加到系统时,我不能去更改代码。

I need to convert above formats into simple format like 'd-m'Y'. The problem here is that the formats aren't known in advance and I can't go and change the code every time a new CSV files needs to be added to system.

有没有办法可以将所有这些格式转换成简单的格式?我已经尝试下面,但它不起作用,我找不到任何其他解决方案。

Is there a way using which I can convert all these formats into simple format? I've tried below but it doesn't work and I can't find any other solution.

  $date = DateTime::createFromFormat(strtotime('2013-12-04 11:32:21 +0000'), '2013-12-04 11:32:21 +0000'); 
  print_r($date->format('d-m-Y')); //Doesn't work

提前感谢您的帮助。

推荐答案

PHP了解很多的日期格式。在这里不需要使用 DateTime :: createFromFormat()。简单地将你的日期字符串传递给 DateTime 构造并格式化:

PHP understands a lot of date formats. It's not required to use DateTime::createFromFormat() here. Simply pass your date string to the DateTime construct and format it on the go:

示例:

$array = [
  '2013-12-04 11:32:21 +0000',
  '04/12/2014 +0000',
  '04/12/2014 +0000 11:32:21',
  'Fri Mar 14 18:19:26 +0000 2014',
];

foreach ($array as $datestr) {
    $dt = new DateTime($datestr);
    echo $dt->format('Y-m-d') . "\n";
}

输出:

2013-12-04
2014-04-12
2014-04-12
2014-03-14

演示

这篇关于创建格式未知的日期/时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆