PHP - Formatting a Date - php

I have a date stored into a string variable as such: Sun Jun 02 08:54:12 EDT 2013. How can I convert this into a date variable to compare the time difference between the current date and the date provided. Thanks!

Use the DateTime class to compare the current date with the timestring. Once you have the DateTime objects you can easily get the difference using the method DateTime::diff(). It will return a DateInterval object that can be printed using it's format() method.
$dt = new DateTime('Sun Jun 02 08:54:12');
$now = new DateTime();
if($now > $dt) {
$difference = $now->diff($dt);
echo $difference->format('The time is %H hours %I minutes %S seconds in the past');
} else if ($now < $dt) {
$difference = $dt->diff($now);
echo $difference->format('The time is %H hours %I minutes %S seconds in the future');
} else {
echo 'the time is now';
}
Note: Of course you'll have to extend the output in a way that it displays the difference in years, months and days additionally. I didn't that in the example, because I'm lazy ... aehhmm because the string would get too long for the example ... ;)

Related

How to check if the difference between 2 dates is bigger than 15 minutes?

I am using this function to compare a date from the database to the current date, and i need to check if the difference between the 2 dates is bigger than 15 minutes but i don't know how to do that, i think i need to do something like if($comp > 0 days 0 hours 15 minutes)
function TimeOut($dateP){
$date = new DateTime(date('Y-m-d H:i:s'));
$date2 = new DateTime($dateP);
echo $comp = $date->diff($date2)->format("%d days %h hours and %i minuts %s seconds");
if ($comp > "15 minutes ?") {
return true;
}
}
You can use diff and then read the m parameter of the result. In the example below $difference will be DateInterval object:
$difference = $start_date->diff($date2);
if($difference->i > 15) {
echo "difference greater than 15 minutes"
}
A date interval stores either a fixed amount of time (in years,
months, days, hours etc) or a relative time string in the format that
DateTime's constructor supports.

Unable to get time difference between two dates

I am trying to find the time difference between an expiry date and today's date, but my code doesn't work.
$time_one=DateTime::createFromFormat('d/m/Y', get_field('expirydate'));
$time_two=new DateTime();
$timeleft = $time_one->diff($time_two);
echo $timeleft;
Try:
echo $timeleft->format('%a days');
So when you apply diff function to DateTime object -> you receive a DateInterval object. To access its properties about total difference between dates you should apply method called format.
The diff method returns you an DateInterval object. You must format the output in order to see how many days, hours, minutes, seconds remained:
$dateTimeInTheFuture = DateTime::createFromFormat('d/m/Y', get_field('expirydate'));
$dateInterval = $dateTimeInTheFuture->diff(new DateTime());
echo 'Time remained until expire: ' . $dateInterval->format('%d days, %h hours, %i minutes, %s seconds');
Read more about DateInterval.format method

New date format from Twitter

So, I am implementing twitter via twitter widget pro into a wordpress theme. I'm wanting to date the tweets differently from wordpress and from the widgets formats. I want to follow twitters date format of 5h, 23h, or 3 Mar. All I've been able to find is how to do the "created _ ago" "about _ old" etc... I just want to use the xh if within 24 hours, otherwise use the day and month abbreviation. I really don't know php or too much js, so any help is very very much appreciated.
Use PHP DateTime and DateInterval classes,
$dt1 = new DateTime("2012-02-10 10:32:22");
$dt2 = new DateTime();
$diff = $dt2->diff($dt1);
echo $diff->format("%Y years, %m months, %d days, %H hours, %I minuts, %s seconds ago");
/// 00 years, 1 months, 18 days, 08 hours, 26 minuts, 51 seconds ago
If you dont want to echo 00 years, 00 months etc then check DateTime::y, DateTime::m etc properties is 0. if zero dont echo them. For example,
$format = "";
if ($diff->y > 0){
$format.="%Y years,";
}
if ($diff->m > 0){
$format.="%m months,";
}
...
// more conditions for hours, minutes, seconds
// echo the format
echo $diff->format($format);
Links of Interest,
DateTime::__construct()
DateTime::diff()
DateInterval::format()

Count total month

I have to find total months between two dates in Unix timestamp formats. I want to create a PHP function for that. I've tried this:
get_total_month($startunixdate, $endunixdate) {
$monthdiff = $endunixdate-$startunixdate;
$monthdiff = $monthdiff / 60*60*24*31;
return $monthdiff;
}
Does this function consider leap years as well as month with 30 and 31 separately, or it will just count an approximate month?
Your answer is in this line;
$monthdiff = $monthdiff / 60*60*24*31
This will just count a month based on 31 days. The code divides the seconds by 60 to get the number of minutes, 60 again to get hours, 24 to get number of days, then it uses 31 as the length of a month.
This will result in an approximation of the number of months. For instance, if you take timestamps at the beginning and end of February (start of March), you will usually have a timestamp difference equivalent to 28 days (29 in a leap year). Dividing that by 31 will give you a fraction less than 1, since you are using 31 to represent a full month, when in reality a whole calendar month has passed.
In order to do this, use the DateTime class.
function get_total_month($start, $end) {
// Create DateTime objects
$dt1 = new DateTime($start);
$dt2 = new DateTime($end);
// Get DateInterval object representing difference between the two
$diff = $dt1->diff($dt2); // OR: $diff = date_diff($dt1, $dt2);
// Print the "months" out
echo $diff->format("Difference: %R%m months"); // OR access $diff->m manually
U can use PHP 5.3 datetime method.
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
Reference: PHP DateTime

formatting mysql timestamp in php, with several conditions

I'm trying to format a SQL timestamp in PHP based on the following conditions, but can't figure out how. Can anyone point me in the right direction?
If the timestamp was TODAY, display as 4:15PM or 12:30AM
If the timestamp was before TODAY but in the past 7 DAYS, list as 'Sunday' or 'Monday'
If the timestamp was before 7 DAYS ago, list as 'mm/dd/yy'
How would I go about that?
First you need to convert the MySQL time to a unix timestamp which is what most of php date functions use. If you are using MySQLs DateTime type, you can perform the conversion in SQL with the MySQL function unix_timestamp() mysql date functions. Or you can convert the mysql date to a unix timestamp in PHP with the strtotime($mysqlDateTime) function php strtotime function
once you have the unix timestamp of the time you would like to format, the conversion would look something like this (86400 is number of seconds in 24 hours):
function displayDate($timestamp)
{
$secAgo = time() - $timestamp;
// 1 day
if ($secAgo < 86400)
return date('h:i:A', $timestamp);
// 1 week
if ($secAgo < (86400 * 7))
return date('l', $timestamp);
// older than 1 week
return date('m/t/y', $timestamp);
}
This method has the benefit of not requiring extra object creation in PHP (a tad slow) or performing unnecessary calculations on the SQL server. It might also help to know that MySQL's timestamp type stores data as a unix timestamp (number of seconds since Jan 1 1970) value requiring only 32bits for storage compared to datetime which uses 64bits of storage. 32 bits should be enough for everyone, until 2038 or something....
you can check date difference by by diff() of PHP or by msql datediff()
http://www.php.net/manual/en/datetime.diff.php
Then check difference is zero or equal to 1 or greater than 7
h 12-hour format of an hour with leading zeros 01 through 12 date('H:i:s')
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59
G 24-hour format of an hour without leading zeros 0 through 23
USE DATE(G) to find AM or PM
if($TODAY)
date('h:i:s')PM
ELSE IF ($THISWEEK)
l (lowercase 'L') A
full textual representation of the day of the week Sunday through Saturday
ELSE IF($BEFOREONEWEEK)
date('d-m-y')
http://php.net/manual/en/function.date.php
This should work. Hope so :-)
You just have to use a conditional:
$now = new DateTime("now");
$ystrday = new DateTime("yesterday");
$weekAgo = new DateTime("now")->sub(new DateInterval('P7D'));
$inputDate = new DateTime(whenever);
if($yesterday < $inputDate and $inputDate < $now){
$outDate = date('g:ia', $inputDate->getTimestamp() );
}else if($weekAgo < $inputDate and $inputDate < $now){
$outDate = date('l', $inputDate->getTimestamp() );
}else if($inputDate < $weekAgo){
$outDate = date('d/m/y', $inputDate->getTimestamp() );
}
This hasn't been tested and you'll need to get your mySql date into a php DateTime object but it should get you pretty close.
I assume you're talking about the MySQL TIMESTAMP datatype, since I don't think MySQL actually has a datatype like a Unix timestamp (i.e. seconds since epoch), so you'll have to first convert the date you get using the strtotime function:
$timestamp = strtotime($dbTimestamp);
This will return a Unix timestamp you can play with.
Next we'll define a couple more timestamps to compare this value against:
First, we want to know the timestamp for midnight this morning. For that, you'll pass the string "today" to strtotime:
$today = strtotime("today");
Next, we need to know the timestamp for seven days ago. You'll have to choose between "1 week ago" and "1 week ago midnight". The difference between these two is that midnight will return the timestamp for 12am on that day, while the version without it will return the current time, seven days ago (e.g. today, the difference would be that midnight will return 12 AM on April 7 and the non-midnight version would, right now, return 3:45PM on April 7):
$weekAgo = strtotime("1 week ago midnight");
(Note, there are many formats that strtotime understands, including many relative formats like the "today" and "1 week ago" examples used above.)
Next, we need to define the date formats to use in each case:
$timeOnly = "g:i A"; // This gives an "hour:minute AM/PM" format, e.g. "6:42 PM"
$dayOfWeek = "l" // Gives a full-word day of the week, e.g. "Sunday"
$mdy = "m/d/Y" // gives two-digit month and day, and 4-digit year,
// separated by slashes, e.g. "04/14/2011"
Finally, we just do our comparisons, and format our timestamp using the date function:
if ($timestamp >= $today) {
$date = date($timeOnly, $timestamp);
} elseif ($timestamp >= $weekAgo) {
$date = date($dayOfWeek, $timestamp);
} else {
$date = date($mdy, $timestamp);
}
This will leave you with a string variable called $date which contains your database-provided timestamp in the appropriate format, which you can display on your page as needed.

Categories