質問

I'm using the Twitter API to get my recent tweets from an XML file into my website. I already have the tweets displaying on my page but I can't get it to show how many days have passed since the displaying tweet.

I've already tried some solutions answered here for the same problem but it didn't work for me. The Date and Time from the XML file are given as folows:

<statuses type="array">
   <status>
      <created_at>Sat Mar 23 18:43:16 +0000 2013</created_at>
   </status>
</statuses>

I'm retrieving the data like this:

<?php
$xmldata = 'https://api.twitter.com/1/statuses/user_timeline.xml?screen_name=AblazeDigital';
$open = fopen($xmldata, 'r');
$content = stream_get_contents($open);
fclose($open);
$xml = new SimpleXMLElement($content);
?>
<?php 
    echo $xml->status[0]->created_at;
?>

How can I make a function with php the reads the follwing date "Sat Mar 23 18:43:16 +0000 2013" and tells how many days have passed to the present day?

役に立ちましたか?

解決 4

$now = new DateTime('NOW');
$pageTime = new DateTime('Sat Mar 23 18:43:16 +0000 2013');

$sub = $now->diff($pageTime);
$days = $sub->format('%d');

if ($days < 1) {
    echo 'Less than a day has passed';
}
elseif ($days == 1) {
    echo $days.' day has passed';
}
else {
    echo $days.' days have passed';
}

他のヒント

$now = new DateTime();
$postdate = DateTime::createFromFormat("D M d H:i:s P Y", "Sat Mar 23 18:43:16 +0000 2013");
$interval = $now->diff($postdate);
echo $interval->format('%d days');

See it in action

$time = strtotime($xml->status[0]->created_at);
$days = (time() - $time) / 86400 //86400 = seconds of one day

strtotime converts any date string to a unixtime, so if you subtract that from the current time, you get the seconds since the tweet. To convert that to days, simply divide it with 86400.

Use strtotime() and compare it with the current timestamp.

$date = $xml->status[0]->created_at;
$difference = time() - strtotime($date);
$days = $difference/24/3600;
echo $days . " days"; // outputs something like "0.857615740741 days"

See DEMO.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top