Past textual date to days (since) PHP - php

Hey guys,
how does one calculate the days past since a date like the one Twitter outputs in its API
eg:
Mon Jul 12 00:27:26 +0000 2010
to XXX
Can we do it with strtotime
Thanks guys,
Dex

Compatibility note: works only for PHP >= 5.3.0
Providing that the date format does not change, you can reverse the process (i.e. reverse timestamp -> string (on Twitters servers) to timestamp) using the exact date format. Using the table on the manual page of DateTime::createFromFormat:
<?php
$str = 'Mon Jul 12 00:27:26 +0000 2010';
$oDateTime = DateTime::createFromFormat('D M d H:i:s T Y', $str);
$unix_timestamp = $oDateTime->getTimestamp();
echo $unix_timestamp;
?>
Beware: On my machine, date('d-m-Y H:i:s', $unix_timestamp) differs two hours, the machines timezone is GMT+2.
To calculate the difference between in days between two Unix timestamps, use math (a day has 86400 seconds):
echo ($unix_timestamp1 - $unix_timestamp2) / 86400;
If you've two such dates, you can use DateTime::diff as suggested in the comments by Zerocrates. You've create two DateTime instances using DateTime::createFromFormat and invoke the DateTime::diff with two arguments passed, previously created DateTime instances. The returned DateInterval instance has a d property which contains the difference in days.
The other way would be using the getTimestamp method, doing the maths from the previous example.
References:
http://php.net/manual/en/datetime.createfromformat.php
http://php.net/manual/en/datetime.gettimestamp.php
http://www.php.net/manual/en/datetime.diff.php
http://www.php.net/manual/en/class.dateinterval.php

You can do it like that (where $your_date is the string you mentioned):
$diff = (time() - strtotime($your_date)) / (24*60*60);
In your case, when I did echo $diff; the output was (at the time I posted the answer):
321.85475694444
See more details for strtotime(), time() and date().
Hope this helped you.

You might find sth here:
performing datetime related operations in PHP
or in php manual there is a lot..
http://php.net/manual/en/function.date.php

Related

php timestamp to readable date not working as expected

Im trying to convert my timestamp to a readable date (going to be used in a sql query).
My code:
$date1 = date("d-m-Y",Input::get('van'));
return Input::get('van')." ".$date1;
The timestamp:
1451602800000
the result
15-12-1966
When i try this application the result of that timestamp is Thu, 31 Dec
2015 23:00:00 GMT
Which is what i was expecting.
What am i doing wrong that makes me get the wrong day-month year? the timestamp seems to be oke the code is the accepted answer here:
Adding:
date_default_timezone_set('UTC');
dosn't change anything
Remove three zeros from the right of your timestamp. A Unix timestamp is represented in seconds, not milliseconds.
$date1 = date('d-m-Y', Input::get('van') / 1000);
return Input::get('van') . ' ' . $date1;
See the time function for an example of an acceptable timestamp that can be used with the date function.
You probably use Laravel, so this package it integrated:
https://github.com/briannesbitt/Carbon
And try this tutorial to get up to speed:
https://scotch.io/tutorials/easier-datetime-in-laravel-and-php-with-carbon

Convert google analytics date to human readable value

I am getting Google Analytics data via API using google-api-php-client
Everything fine except one thing, I can't convert day timestamp into readable value. The day timestamp looks like 20150724, date('M j', $date); always shows Aug 22 even for different timestamps.
How to fix it?
If you don't tell PHP what the number is, it will assume it's a UNIX timestamp. 20150724 is 22nd August 1970...
So just tell it how it's formatted:
<?php
$google_date = '20150724';
$date = DateTime::createFromFormat('Ymd', $google_date);
echo $date->format('M j');
date() expects the $date to be a timestamp which is the number of seconds since the Unix epoch. Try converting $date with strtotime.

Compare timestamp to date

I need to compare a timestamp to a date. I would just like to compare the date portion without the time bit. I need to check whether a timestamp occurs on the day before yesterday i.e. today - 2.
Could you show me a snippet please? Thank you.
I've been reading through the PHP docs but couldn't find a very clean way of doing this. What I found was converting the timestamp to a date with a particular format and comparing it to a date which I get by doing a time delta to get the date before yesterday and converting it to a particular format. Messy.
You can arcieve this by using the function strtotime.
To round to a day I personaly like to edit the timestamp. This is a notations of seconds since epoch. One day is 86400 seconds, so if you do the following caculation:
$time = $time - ( $time % 86400 );
You can convert it back to a date again with the date function of PHP, for example:
$readableFormat = date( 'd-m-Y', $time );
There is also much on the internet about this topic.
you can use the strtotime function
<?php
$time = strtotime("5 june 2010");
$before = strtotime("-1 day",$time);
$after = strtotime("+1 day",$time);

PHP date format converting

Here is what I have:
$dateFormat = 'M d, Y';
$dateString = 'January 23, 2010';
What I need is a timestamp of $dateString so I can do this:
$newFormattedDate = date('Y-m-d', $timestamp);
I tried to use strtotime function but it tries to find out the format itself and doesn't work always. In my situation I know both the date string and date format.
How can I set $timestamp to an appropriate value for use with the date function?
EDIT: I need this to work in both Linux and Windows environments.
EDIT: The solution must support PHP version 4 or higher
EDIT: MySQL has a function called STR_TO_DATE which takes a date string and a date format and returns Y-m-d formatted date string. Any equivalent function for php works for me also.
As of PHP5.3 you can use the DateTime API
$dt = date_create_from_format('M d, Y', 'January 23, 2010');
echo date_timestamp_get($dt);
or with OOP notation
$dt = DateTime::createFromFormat('M d, Y', 'January 23, 2010');
echo $dt->getTimestamp();
Note that while DateTime is available in PHP < 5.3, the methods used above are not and while you could simulate ->getTimestamp() with ->format('U'), there is no easy workaround for createFromFormat()
An alternative would be to use Zend_Date from Zend Framework:
$date = new Zend_Date('Feb 31, 2007', 'MM.dd.yyyy');
echo $date->get(Zend_Date::TIMESTAMP);
Use strptime, mktime and strftime:
$ftime = strptime($dateString, $dateFormat);
$timestamp = mktime($ftime['tm_hour'], $ftime['tm_min'], $ftime['tm_sec'], 1,
$ftime['tm_yday'] + 1, $ftime['tm_year'] + 1900);
echo strftime('Y-m-d', $timestamp);
Please note that strptime is not implemented on Windows platforms.
Note that the arguments to mktime are somewhat unusual - strptime returns a day of the year (between 0-365, inclusive) rather than a day of the month and a month, so we set the month parameter to mktime to 1, and add 1 to the day of the year. Also, strptime returns years since 1900 for the year value it returns, so we need to add 1900 to the year before passing it through to mktime.
Also, you might want to check whether $ftime is FALSE before passing it into mktime. strptime returning FALSE denotes that the inputs $dateString is not a valid date format according to $dateFormat.
Given my understanding of the question and what is available in PHP, you need to relax your expectations somewhere or other.
A 'simple' solution (which has already been discounted) would be to force using PHP 5.3 and the tools available in it.
A less simple solution would be to take those additions and port them over to PHP-land (with PHP 4 compatibility, good luck).
Another route of exploration would be to consider the occasions where strtotime does not work for you and working around those limitations.
How widely variant are your format strings? It may be possible to come up with a solution mapping format strings to functions/methods (to do that date parsing) providing they're pretty restricted.
$dateFormat = 'M d, Y'
$timestamp = strtotime($dateString);
echo date($dateFormat, $timestamp);
if i haven't misunderstand your question you can try the code above..

PHP: convert date into seconds?

I've a date like Tue Dec 15 2009. How can I convert it into seconds?
Update:
How can I convert a date formatted as above to Unix timestamp?
I assume by seconds you mean a UNIX timestamp.
strtotime() should help.
You can use the strtotime function to convert that date to a timestamp :
$str = 'Tue Dec 15 2009';
$timestamp = strtotime($str);
And, just to be sure, let's convert it back to a date as a string :
var_dump(date('Y-m-d', $timestamp));
Which gives us :
string '2009-12-15' (length=10)
(Which proves strtotime did understand our date ^^ )
[edit 2012-05-19] as some other questions might point some readers here: Note that strtotime() is not the only solution, and that you should be able to work with the DateTime class, which provides some interesting features -- especially if you are using PHP >= 5.3
In this case, you could use something like the following portion of code :
$str = 'Tue Dec 15 2009';
$format = 'D F d Y';
$dt = DateTime::createFromFormat($format, $str);
$timestamp = $dt->format('U');
DateTime::createFromFormat() allows one to create a DateTime object from almost any date, no matter how it's formated, as you can specify the format you date's in (This method is available with PHP >= 5.3).
And DateTime::format() will allow you to format that object to almost any kind of date format -- including an UNIX Timestamp, as requested here.
You mean like an UNIX-timestamp? Try:
echo strtotime('Tue Dec 15 2009');

Categories