开发者

date problem in php

In my php application I have this code:

<?php echo date("d/m/ Y ",strtotime($row["m_date"]));?>

In it, $row["m_date"] is fetching from a database.

The problem is that all the dates are printing perfectly except 27/2/2011. It's printing 1/1/1970 instead.

The date in the database is fine, 开发者_JS百科and prints correctly in a PDF.


I'll assume you're getting the date from the database as the string 27/2/2011 because that's most probably what happens (correct me if I'm wrong).

PHP considers the string 27/2/2011 as being in the m/d/Y format, not d/m/Y and tries to parse under that assumption. Because the date is not valid under that format strtotime returns false. Giving false as the timestamp parameter to date is taken as 0, which is the timestamp for January 1st 1970.

What you need to do is either get your date in another format (or better still, as a timestamp) from the database, or parse it yourself (say using explode).

Good luck,
Alin


The database should be able to return the date to you as a UNIX timestamp. For example, MySQL has the UNIX_TIMESTAMP() function.

SELECT UNIX_TIMESTAMP(date_column) FROM table;

Postgres has date_part

SELECT DATE_PART('epoch', date_column) FROM table;

Most other databases should have similar features. If you can get the date out as a UNIX time stamp you can pass that directly to date() without having to use strtotime() as well.

All of this does of course assume you're using a temporal datatype for the columns in question (timestamp, datetime, timestamp with time zone, etc) and not just storing a string. You are using a temporal type, right? If not, then why not?


if you are storing the date in the database as a timestamp this should work

<?php echo date("d/m/Y",$row["m_date"]);?>

if you are storing the date in the database as a date or datetime this should work

<?php echo date("d/m/Y",strtotime($row["m_date"]));?>


How is the m_date stored in the databases? Is it a datetime object? Or a string. Problem with strtotime is that it isn't real good at deciphering written dates. So something like 27/2/2011 gives problems while 27/02/2011 gives no problems at all.

So there are 2 solutions:

  1. Make sure all the dates that get entered into the database are of the correct format (dd/mm/yyyy).
  2. Write a regular expression that adds a leading zero to all single characters.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜