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...
Related
I need to create an empty date with DateTime(). So, all zeros. The time should be displayed in that way: 0000:00:0:00:00.
What I have tried:
$date = new DateTime("2019-05-09 12:07");
$date->setTime(0, 0);
$date->setDate(0, 0, 0);
echo $date->format("Y:W:j:H:i");
That outputs
-0001:49:30:00:00
instead of 0000:00:0:00:00
What could I do to achieve a zero datetime?
More an explanation of what is going wrong than how to achieve what you are after - even if it is possible.
From a date point of view - 0 is invalid for both the month and day. In the manual it has the example
Example #2 Values exceeding ranges are added to their parent values
So if you have greater than the number of days in a month, it will make it the next month
In your case it is almost the opposite, having a number less than the start of the month. So 0 as the month and day, it will act as -1, so if you formatted it as
echo $date->format("Y:m:d:H:i");
the output is
-0001:11:30:00:00
So as you can see, the day and month are 0-1 (11 and 30) and this has overflowed into the year with -1.
No, You cannot make a datetime 0000:00:0:00:00 from DateTime()
php > echo (new DateTime("0000-00-00 00:00:00"))->format("Y-W-j H:i");
-0001-49-30 00:00
php > echo (new DateTime())->setISODate(0,0,0)->setTime(0,0,0,0)->format("Y-W-j H:i");
-0001-52-26 00:00
Surely Not..!
although you can create any Date with PHP helper function (that uses DateTime class behind) any of you desire date with Zeor Time only
$date = date_create('now'); // or any '1970-01-01'
$date = date_format($date, 'Y-m-d 00:00:00');
// or
$date = date('Y-m-d 00:00:00', strtotime('2021-12-21'));
// or
$date = date('Y-m-d 00:00:00');
output: "2021-12-21 00:00:00"
you can initialize the time with current time and take difference of the current time after. its a trick you can perfom to get (0000-00-00 00:00:00).
$currentTime = new DateTime('NOW');
$diff = $currentTime->diff(new DateTime('NOW'));
echo $diff->format("%Y-%m-%d %H %i %s");
that will give you 0000-00-00 00:00:00
I am working on generating recurring dates using PHP to process the dates. I have a $startDateTime and $endDateTime. These two variables are for the first date in the series.
If the even repeats every Tuesday I need something along the lines of
$repeatDay = "Tuesday";
$followingDay = strtotime($startDateTime. " following $repeatDay");
Using "next $repeatDay" doesn't work since I am not generating the date from todays date.
EDIT:
It seems that every five loops the time jumps forward an hour in the date. This may be because $start="2014-04-29 11:00:00" and strtotime is only converting the date correctly.
How should I convert 2014-04-29 11:00:00 to a format that strtotime understands?
$firstOccurrence=strtotime($start);
$nextOccurence=strtotime("next $day", $firstOccurrence); //Set the first recurring date for this day
while($nextOccurence<=strtotime($activeUntil)){
echo date("M d, Y H:m:i",$nextOccurence)." | ";
$nextOccurence=strtotime("next $day", $nextOccurence);
}
Maybe it's time to start working with DateTime? It's pretty complex in modyfing dates. For example, creating date time from your $start would look like this:
$start="2014-04-29 11:00:00";
$dateTime=DateTime::createFromFormat("Y-m-d H:m:i", $start);
And as you have $dateTime, you can modify it by one day:
$dateTime->modify('+1 day');
//or just
$dateTime->modify('next tuesday');
//and return it as string
echo $dateTime->format("M d, Y H:m:i");
DateTime understands everything that strtotime does, so it can improve your solution. Try it out yourself, and let me know if this helps.
strtotime() can take 2 parameters. The first is the string and the second is the base timestamp.
Try the following:
// Assuming $startDateTime is a timestamp.
$followingDay = strtotime("next $repeatDay", $startDateTime);
hello i am working with the Date() function i am getting a time that is current and time that is coming from a database to compare the times, but the dates are different:
date_default_timezone_set("America/Los_Angeles"); // set time zone to LA
$date = date("m-d-Y h:i:s"); // current time
$current_time = strtotime($date); // current time in seconds
$get_time = 1357487529; //linux time from the server
$difference = $current_time - $get_time; //seconds that have pass already
$get_date = date("m-d-Y h:i:s", $get_time); // convert the linux time to current time and date
$exploded_get_date = explode(" ", $get_date); //divide the get date into 2 parts by space 0 = date 1 = time
$exploded_current_date = explode(" ", $date); //divide the current date into 2 parts by space 0 = date 1 = time
the results i get are:
01-Sun-2013 07:52:09 //get date
06-01-2013 07:56:25 //current date
1357487785 // current time
1357487529 // get time
256 //difference
why is it saying i have month 1 in the get date, but in the current date is actually month 6 and also the day it says it is Sunday 6, when is Saturday 1? how can i fix this?
m-d-Y is NOT a valid format for parsing. Only you Americans think it's sensible to put the elements in an unsorted order...
Anyway, the point is, what does 06-01-2013 mean? Is it June 1st, or January 6th?
For consistency's sake, the computer assumes January 6th (d-m-Y format).
I would strongly recommend using the Y-m-d H:i:s format, as this is inherently sortable as string due to being fully big-endian.
EDIT: It should be noted that you can just use time() to get the current timestamp.
Your code is VERY redundant:
$date = date("m-d-Y h:i:s"); // current time
$current_time = strtotime($date); // current time in seconds
can be replaced with a simple
$current_time = time();
and
$get_date = date("m-d-Y h:i:s", $get_time); // convert the linux time to current time and date
$exploded_get_date = explode(" ", $get_date); //divide the get date into 2 parts by space 0 = date 1 = time
$exploded_current_date = explode(" ", $date);
could just be
$exploded_date = date('m-d-y', $get_time);
$exploded_time = date('h:i:s', $get_time);
You are wasting a considerable amount of CPU cycles on useless/repetitive and ultimately redundant operations.
And in the greater picture, your error is that PHP's normal and easiest analysed/parsed date/time strings are in yyyy-mm-dd format. You're building mm-dd-yyyy, which is pretty much entirely scrambled. PHP cannot guess properly when you feed it uncertain formats. That means strtotime() is going to screw up and give you incorrect results.
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.
I need to generate two dates in the format YYYY-MM-DD example: 2010-06-09
The end date should be today and start date should be today - 30 days.
How can I generate these 2 dates in the above format?
for the last 30 days so end date is
today and start date is today - 30
days
The strtotime is real friend:
echo date('Y-m-d', strtotime('today - 30 days'));
It's very simple with DateTime class. You can simply pass the string with the relative expression to the constuctor. When you need to get the date as a string in a specific format use format() method.
$endDate = new \DateTime();
$startDate = new \DateTime('-30 days');
// when you need to use them simple format as a string:
echo $endDate->format('Y-m-d');
echo $startDate->format('Y-m-d');