PDA

View Full Version : Wrong Date in PHP


Jamie
June 11th, 2007, 22:40
I'm using some pretty basic PHP to link to the comments in a blog post, but the date in the URL isn't correct, despite the date being correct within WordPress and within the WordPress database.

Here is the code that I'm using.

<?php
$how_many=1; //How many posts do you want to show
require_once("http://www.test.com/wp-config.php"); // Change this for your path to wp-config.php file
?>

<?
$news=$wpdb->get_results("SELECT ID,post_title, post_content, post_date, post_name, comment_count FROM wp_posts WHERE post_status = 'publish' and post_type = 'post' ORDER BY ID DESC LIMIT ".$how_many);

foreach($news as $np) {

$d = strtotime($np->post_date);
$cc = $np->comment_count;
$link_text = ($cc == 1) ? "$cc comment." : "$cc comments.";

echo "<h2>" . $np->post_title . "</h2>";
echo "<p class=\"smalltext\">" . date('M d, Y', strtotime($np->post_date) . "<br />");
echo "<a href='http://www.jamieharrop.com/" . date('Y/m/d',d) . "/" . $np->post_name . "/#comments'>" . $link_text . "</a></p>\n";
echo "<img width=\"78\" height=\"117\" src=\"wp-content/themes/vertigo-3column/graphics/man_thinking.gif\" alt=\"\" class=\"float_image\" />";
echo "<p>" . $np->post_content . "</p><br />";
echo "<a href='http://www.jamieharrop.com/" . date('Y/m/d',d) . "/" . $np->post_name . "/#comments'>" . $link_text . "</a></p>\n";
}
?>

It's the last echo which isn't working as intended (It's the same as the third echo too).

The date is being outputted as 1969/12/31 (Or 31st Dec 1969). It should be outputting as 2007/05/31 (Or 31st May 2007) like the second echo does.

Maybe it's something to do with the forward slashes between each date item? I need those there because they form part of the URL.

Any ideas?

Gerrit
June 11th, 2007, 22:55
Not checked but I think you should do something like:

date('Y') . "/" . date('m') . "/" . etc.

Did you try that?

Jamie
June 11th, 2007, 23:25
That gets us somewhere, Gerrit.

When I use it, it outputs todays date.

Any idea how I would pull the date from the 'post_date' database field, put it in the Y/M/D order and contain it within the link?

I don't ask much, do I? :lol:

inimino
June 11th, 2007, 23:45
1970/1/1 is the Unix epoch, the origin for Unix datetime values. Adjusted to your local time zone you can get 1969/12/31. An unexpected date near January 1, 1970 can be a hint that some variable is uninitialized, reset, or mistyped.

In this case:
date('Y/m/d',d)
You used 'd' instead of '$d'. ;)

Jamie
June 11th, 2007, 23:48
Ah drat. I was wondering what that random "d" was for (I didn't write the code). :blush:

Thanks Mj. It works perfectly. :)