formatting mysql timestamp in php, with several conditions - php

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.

Related

Get seconds from a date to end of month PHP

Pulling a date of subscription from an sql database table we want the customer to have until the end of the month one year later to make a payment. The subscription is just some date within a month. The one year later part is easy, figuring out where the end of that month is and adding it, in seconds, to the one year part is giving me problems.
The date is stored as the number of seconds from unix ground zero. How do I find the number of seconds from that value to the end of that month? I've tried converting the date value to an actual date using m-i-Y
End of Month:
$expDate = date('m-i-Y',$row1["renewDate"]);
This works. I get the last day of that month in string form. But if I try:
$endOfMonth = strtotime($expDate);
Doesn't work....
echo'ing $expDate shows the last day of the month in string form.
echo'ing $endOfMonth returns nothing...
Thanks for any thoughts on this.
strtotime doesn't work properly with arbitrary date formats. You have two options:
Use date_create_from_format to parse custom date formats.
Convert your string to Y-m-d format which strtotime understands
automatically.
For example:
$date = date('Y-m-t', $row1["renewDate"]);
$timestamp = strtotime($date);
P.S. As mentioned in comments, you should use t instead of i.
You can play around with something like this. If the database has Epoch time then you can use the '#' symbol to convert it to a date. You can get the subscription date that way, and also the end of the subscription month date using m/t/Y. You can convert that back to DT and then to UNIX time with get Timestamp. Looks like it works for time = 1560961801.
$row1["renewDate"] = 1560961801;
$unixfromDB = $row1["renewDate"];
$date = new DateTime('#' .$unixfromDB); // your UNIX timestamp.
$subdate = $date->format( 'm/d/Y' ); // subscription date
$endmonth = $date->format( 'm/t/Y' ); // end of month date
$endmonth = DateTime::createFromFormat('m/d/Y', $endmonth);
$endmonth = $endmonth->getTimestamp(); // UNIX timestamp for end of month.
echo ($endmonth - $unixfromDB) / (60 * 60 *24); // days to end of month
Try using mktime() instead of strtotime().
<?
/* establish variables */
$now=time(); // epoch seconds right now
$expDate = date('m-t-Y', $row1["renewDate"]); //note the switch to 't' as suggested by #ehymel
$eom = mktime($expDate); // converts 'end of month' date into epoch seconds
/* results */
$secondsleft = $eom - $now; // number of seconds until the end of the month
echo $secondsleft; // return results
?>
mktime($expDate) unfortunately didn't work, at least with CentOS6.9. Even with the expdate variable it still returned current system time.
Using the date format that strtotime would recognize, Y-m-t, did work correctly. Thanks user1597430...

Add variable string to datetime eg. 2 weeks

is it possible to add a variable string like '2 day, 2 weeks or even 4 hours' to a date time in PHP.
For example:
I have a date time like this: '2017-08-02 12:00'
now the user choose an interval like '4 hours or 2 weeks'
now the user choice should be added to the date time.
Is this possible?
I don't want the whole code, maybe just an advice how to do that.
thanks
Yes, use
$userDate = strtotime('2017-08-02 12:00:00');
echo date('Y-m-d H:i:s', strtotime('+4 hours', $userDate));
to get date after 4 hours
Example
Explanation
strtotime converts about any English textual datetime description into a Unix timestamp. Most commonly it's used with actual date string or with difference string. E.g. +5 months, 'next Monday' and so on. It will return Unix timestamp - integer that represents how much seconds there is after 1970-01-01 (1970-01-01 00:00:00 is 0, 1970-01-01 00:01:00 is 60 and so on).
So in strtotime('2017-08-02 12:00:00') we convert date to integer for later use.
strtotime('+4 hours', $userDate) - here we use our date as "now" parameter (by default it's time()) and requesting to return timestamp after 4 hours.
echo date('Y-m-d H:i:s', ...); - date accepts format and Unix timestamp to convert from integer back to human readable text.
May be you are looking for this:
http://php.net/manual/en/datetime.modify.php
$date = new DateTime('2006-12-12');
$date->modify('+1 day');
echo $date->format('Y-m-d');
For a datetime you can use the add method but you have to put in the correct code for the amount to add.
$my_date = new DateTime();
$addition = 4;
$my_new_date = $my_date->add(new DateInterval("P${addition}D"));
echo $my_new_date->format('Y-m-d H:i:s');
Where addition is your variable that you want to add.

convert a date into a timestamp [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 6 years ago.
Okay so basically I have two variables one called $day and another called $time what I'm trying to do is convert both of these into a unix time-stamp so for example;
$day = 'Monday';
$time = '14:00:00';
So what I'm looking for is a $timestamp variable that would echo out the next Monday coming up at 14:00:00 in a unix timestamp format.
I'm guessing the hardest part of this would be the fact that the day is not a specific date more a day of the week meaning it would have to select the next monday coming up, or the next tuesday... for example.
Thanks for any help.
The constructor for the DateTime class is pretty good at figuring this sort of thing out:
<?php
$day = 'Monday';
$time = '14:00:00';
$date = new DateTime("next $day $time");
echo $date->getTimestamp();
// 1475503200
$datetime = new DateTime();
echo $datetime->format('U');
Solution One:
mktime - Get Unix timestamp for a date
echo mktime(23, 24, 0, 11, 3, 2009);
1257290640
Returns the Unix timestamp corresponding to the arguments given. This timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.
Arguments may be left out in order from right to left; any arguments thus omitted will be set to the current value according to the local date and time.
mktime($isAM ? $hrs : ($hrs + 12), $mins, $secs, $m, $d, $y);
To handle AM/PM just add 12 to hours if PM.
Solution Two:
strtotime Returns a timestamp on success, FALSE otherwise.
echo strtotime('2012-07-25 14:35:08' );
Output:
1343219708

PHP: get next date based on fixed base date

is there a way in PHP to get the next date(s) using a 4-week interval from a given date ?
Example:
My start date is Friday, Jan 03, 2014 and my interval is every 4 weeks from that date.
What I am looking for is the next date (or dates, if possible) from the current date that matches this 4-week interval.
In the above example this would be Friday, May 23, 2014 (then June 20, 2014, July 18, 2014 etc.).
I know I can get the current date as follows: $today = date('Y-m-d');
and I could probably set the start date like this: $start = date('2014-01-03');
but I don't know how to calculate the interval and how to find out the next matching date(s).
You should read up on the DateTime classes, specifically DatePeriod and DateInterval:
$start = new DateTime('2014-01-03');
$interval = DateInterval::createFromDateString('4 weeks');
$end = new DateTime('2015-12-31');
$occurrences = new DatePeriod($start, $interval, $end);
foreach ($occurrences as $occurrence) {
echo $occurrence->format('Y-m-d') . PHP_EOL;
}
DatePeriod takes a start date and a DateInterval and allows you traverse over the object to get all dates within the boundaries using the given interval. The cut off can be either a set number of cycles (so the next 10 dates) or an end date (like above), even if the end date is not one of the dates the interval falls on (it will stop below it). Or you can use an 8601 interval notation string (which sounds so much fun, huh?), but I'm pretty shaky on that.
If 4-week interval means 7 x 4 = 28 days, you can obtain the "next date" by:
$today = new DateTime();
$next_date = $today->add(new DateInterval('P28D'));
$next_next_date = $next_date->add(new DateInterval('P28D'));
$next_next_next_date = $next_next_date->add(new DateInterval('P28D'));
And if you want to calculate more "next dates", you can repeat the add() to repetitively add 28 days to your date.
Note: Beside using P28D, you can use P4W, which means 4 weeks.
While some answers may suggest using strtotime(), I find the object-oriented approach more structured. However, DateInterval is only available after PHP >= 5.3.0 (while DateTime is available after PHP >= 5.2.0)
You could use strtotime()
echo date('Y-m-d', strtotime('now +4 weeks'));
UPDATED:
$start = date('Y-m-d', strtotime('2014-01-03 +4 weeks'));
echo $start;
You could also run this in a for loop to get the next 6 or more dates. For example:
$Date = "2014-01-03";
$Int = 6;
for($i=0; $i<$Int; $i++){
$Date = date('Y-m-d', strtotime('{$Date} +4 weeks'));
echo $Date;
}

PHP one week ago from a specific date

so i have a date format like 07-09-10 and i want to know how to get ago from that date and if i can have a conditional like
if(is_date_with_1_week_of_above_date){
//do something
}
For checking date with relation to the Current Timestamp
if( strtotime( '-1 week' )>=$dateToCheck ) {
# $dateToCheck is within the last week
}
The other responses have good solutions for simple checking whether two date/times are within 1 week of each other - no point me repeating them.
Your date doesn't make clear the format (is it MM-DD-YY, DD-MM-YY, YY-MM-DD, etc.)? But an example using ISO 8601 date format is this:
$oneWeekAgo = strftime("%Y-%m-%d", strtotime("2010-07-09") - 60*60*24*7);
For a comparison, you can use the UNIX timestamp values
$date = "2010-07-09";
$compareDate = "2010-07-03";
$curTimestamp = strtotime($date);
$compareTimestamp = strtotime($compareDate);
if(abs($curTimestamp - $compareTimestamp) < 60*60*24*7)
{
// within 1 week
}
Edit
Per the comment on the date format, dd-mm-yy is a recognized format for dates, but mm-dd-yy is not in strtotime as seen here:
http://www.php.net/manual/en/datetime.formats.date.php
For it to work, you'd have to convert the dashes to slashes.
Also, if you're looking if the date is specifically one week prior,
$date = str_replace('-','/',"07-10-10");
$compareDate = str_replace('-','/',"07-03-10");
$curDate = strftime("%m/%d/%y", strtotime($date));
$compareDate = strftime("%m/%d/%y", strtotime($compareDate) + 60*60*24*7);
if($curDate == $compareDate)
{
// is one week prior
echo "OK";
}
Depending on your Time Zone, some days might have only 23 hours, so you can not use as a rule that a day has (60 seconds * 60 minutes * 24 hours) and with this, to calculate a specific date.
Specifying a date:
$specific_date = date( "Y-m-d" ); // for today
or
$specific_date = date( "Y-m-d", $timestamp ); // where timestamp is: Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
The answer will be
$date = strtotime( $specific_date . " -1 week" );

Categories