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.
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 have tried to solve it by extracting the numeric part and then parsed it using date function. But it shows me some old date which I guess is not correct.
$datef = "1490914800000+0100";
$adada = date('Y-m-d H:i:s', $datef);
// Gives date 1987-10-13 18:31:28 which is an old date. Please suggest.
One approach, well-covered by this SO question, is to use the DateTime() function to convert time in seconds since epoch to a date, and then display this date using format(). But there are two caveats with your data. First, you appear to have milliseconds since the epoch, which needs to be converted to seconds. Second, you also have a timezone shift, in hours, tagged to the end. I split your $datef string into two parts, epoch and timezone, then arrive at the number of seconds since epoch.
list($epoch, $timezone) = explode('+', $datef);
$epoch = ($epoch / 1000) + (substr($timezone, 0, 2)*60*60) +
(substr($timezone, 2, 2)*60);
$dt = new DateTime("#$epoch");
echo $dt->format('Y-m-d H:i:s');
Output:
2017-03-31 00:00:00
Demo here:
PHP Sandbox
The time seems to be in milliseconds.
You can add the timezone shift to the seconds. 1 hour = 3600 seconds.
$milliSeconds = intval("1490914800000");
$seconds = $milliSeconds/1000;
$date = date("Y-m-d H:i:s", $seconds);
How do I get future dates with:
https://github.com/fzaninotto/Faker#fakerproviderdatetime
dateTime($max = 'now')
i.e. what should the $max value be for datetime in the future
You can pass strtotime string conditions to $faker->dateTimeBetween().
//ranging from today ending in 2 years
$faker->dateTimeBetween('+0 days', '+2 years')
//ranging from next week ending in 1 month
$faker->dateTimeBetween('+1 week', '+1 month')
//ranging from next sunday to next wednesday (if today is wednesday)
$faker->dateTimeBetween('next sunday', 'next wednesday')
see http://php.net/manual/en/function.strtotime.php for a full list of string usages and combinations.
Try passing a unix timestamp for $max:
$unixTimestamp = '1461067200'; // = 2016-04-19T12:00:00+00:00 in ISO 8601
echo $faker->dateTime($unixTimestamp);
echo $faker->date('Y-m-d', $unixTimestamp);
// for all rows
$faker->dateTimeBetween('now', $unixTimestamp);
Or pass a strtotime timestring to $faker->dateTimeBetween():
// between now and +30y
$faker->dateTimeBetween('now', '+30 years');
To get date for a tomorrow. We can use this.
$faker->dateTimeBetween('now', '+01 days');
Or for future date, we can use php strtotime function as #mshaps already mentioned.
Try this:
$faker -> dateTimeThisDecade($max = '+10 years')
Given a date string formatted Y-m-d (2014-4-11 for example), how can I get a UNIX timestamp of 12am the beginning of that day? Would it involve date_parse_from_format()?
Thanks
You can simply use strtotime()
$date = "2014-04-11";
$timestamp = strtotime($date);
which inturm gives you -
$d = date('Y-m-d H:i:s', $timestamp); // 2014-04-11 00:00:00
Try online conversion to test - http://www.onlineconversion.com/unix_time.htm
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.