简体   繁体   English

PHP - 更改日期格式

[英]PHP - Changing date format

Im getting a result from a SQL query im running which outputs the following date ($mydate) (05/02/2011) .... It is formatted as dd/mm/yyyy ... When i run 我从运行的SQL查询得到一个结果输出以下日期($ mydate)(05/02/2011)....格式为dd / mm / yyyy ...当我运行

date('l jS \of F Y',strtotime($mydate))

Im getting a completely different date to what is inputted, im gathering this is because im not using the mm/dd/yyyy format. 我得到一个完全不同的日期输入,我收集这是因为我不使用mm / dd / yyyy格式。

How would i go about swapping it around for it to work properly? 我将如何交换它以使其正常工作?

Cheers. 干杯。

You could use strptime() to parse the date/time format. 您可以使用strptime()来解析日期/时间格式。 You could also convert the date string to YYYY-MM-DD which is always parsed correctly by strtotime. 您还可以将日期字符串转换为YYYY-MM-DD,它始终由strtotime正确解析。 Eg: 例如:

$date = implode('-', array_reverse(explode('/', $date)));

But I agree with the other answers. 但我同意其他答案。 Have a look at your database settings first. 首先查看您的数据库设置。 Virtually all databases are able to output YYYY-MM-DD format directly, and most will do so by default. 几乎所有数据库都能够直接输出YYYY-MM-DD格式,大多数数据库默认都会这样做。 See why yours doesn't. 看看为什么你没有。

I wonder why your date is coming out of your DB as dd/mm/yyyy, what kind of DB are you using? 我想知道为什么你的数据库的日期是dd / mm / yyyy,你使用的是什么类型的数据库? If MySQL, a DATE field should output YYYY-MM-DD which will behave correctly with strtotime(). 如果MySQL,DATE字段应该输出YYYY-MM-DD,它将使用strtotime()正常运行。

You could explode('/', $mydate) to manually split dd, mm and yyyy, and then reconstruct a new date string, or directly use the resulting numbers with mktime(). 你可以explode('/', $mydate)来手动拆分dd,mm和yyyy,然后重建一个新的日期字符串,或直接使用mktime()生成的数字。

Here is a list of formats which strtotime() understands. 以下strtotime()理解的格式列表。

Which SQL outputs such a weird date format? 哪个SQL输出这种奇怪的日期格式? Or did you format the date yourself? 或者你自己格式化日期?

If it always comes in that format, you can use 如果它始终以该格式出现,您可以使用

$newtime = preg_replace("/\d\d\/\d\d/\d\d\d\d/", "$3/$2/$1", $date);

To convert it to yyyy/mm/dd, then just plug that into strtotime() 要将其转换为yyyy / mm / dd,然后将其插入strtotime()

It's definitely not the most elegant solution, I would actually suggest reworking the database (create a new column, run a script to read each entry, generate the new date, then input that in, delete the old date field, then rename the new one, so this only has to be done once). 它绝对不是最优雅的解决方案,我实际上建议重新编写数据库(创建一个新列,运行脚本来读取每个条目,生成新日期,然后输入,删除旧日期字段,然后重命名新日期,所以这只需要做一次)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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