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" );
Related
I am trying to compare two times one of which is in 12 hour format and the other is in 24 hour format, that is after 12am.
$time = date( 'H:i:s', current_time( 'timestamp', 0 ));
$open = '18:00';
$closed = '01:30';
if ( $time < $open || $time > $closed)
{
//do something
}
this is always failing it is something to do with the 01.30 because if I do anything less than 00:00 e.g. 23.30:
$time = date( 'H:i:s', current_time( 'timestamp', 0 ));
$open = '18:00';
$closed = '23:30';
The above works.
I have also tried strtotime like this without success.
if ( $time < strtotime($open) || $time > strtotime($closed))
How can I evaluate between 6pm and 2am in the morning?
Much like when working with months and January being either the first month of this year or 13th month of last year, 1 am is either the 1st hour of today or the 25th hour of tomorrow.
I'd reverse your logic and determine if it is currently greater than 0130 and less than 1800. Take out the colons and it makes it really easy
$close=013000;
$open=180000;
$now=date( 'His', time());
if (($close<$now)&&($now<$open)){
print("Go away, we're closed");
}else{
print("Welcome to the store!");
}
If you don't want to reverse the logic, then instead of using 01:30 use 25:30 for the value - PHP and date are pretty good about rolling over the next position when a larger than max value is used some place.
Since you are only comparing the current time (time right now), logically you don't have to worry about tomorrow's time. You only need to compare if you are inside/outside today's opening/closing times.
<?php
// SET RELEVANT TIMEZONE
date_default_timezone_set('Europe/Dublin');
// CURRENT UNIX TIMESTAMP
$time_now = time();
// TODAY AT 18:00:00 (24 HOUR) UNIX TIMESTAMP
$opening_time = DateTime::createFromFormat('H:i:s', '18:00:00')->format("d-M-Y H:i:s"); // 11-May-2018 18:00:00
// TODAY AT 01:30:00 (24 HOUR) UNIX TIMESTAMP
$closing_time = DateTime::createFromFormat('H:i:s', '01:30:00')->format("d-M-Y H:i:s"); // 11-May-2018 01:30:00
// WE ARE CLOSED IF:
// TIME NOW IS AFTER CLOSING TIME TODAY (01:30:00)
// AND TIME NOW IS BEFORE OPENING TIME TODAY (18:00:00)
if($time_now > strtotime($closing_time) && $time_now < strtotime($opening_time))
{
echo "Sorry, we are closed!";
}
else
{
echo "We are open, come on in!";
}
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.
I can add x week to my date
//$ultima_azione <--- 2015/07/15
//$data['intervallo'] <---- 5
$mydate = date("Y-m-d",strtotime($ultima_azione." +".$data['intervallo']." weeks"));
now how can i give a day starting from that week
example:
//$mydate + "next Monday" -----> final date
and this ve to work like, if today is Monday and i add weeks to jump to an other Monday and then i select the next Monday the week don't ve to change
The simplest way would be to use strtotime. It can do date calculations based on a textual representation of the delta:
$mydate = strtotime('+3 weeks');
It also accepts a second parameter, which is a timestamp to start from when doing the calculation, so after you get the offset in weeks, you can pass the new date to a second calculation:
// Get three weeks from 'now' (no explicit time given)
$mydate = strtotime('+3 weeks');
// Get the Monday after that.
$mydate = strtotime('next Monday', $mydate);
See strtotime documentation for more examples of notations that you can use.
I would highly recommend using PHP's built-in DateTime class for any date and time logic. It's a much better API than the older date and time functions and creates much cleaner and easier to read code.
For example:
// Current date and number of weeks to add
$date = '2015/07/15';
$weeks = 3;
// Create and modify the date.
$dateTime = DateTime::createFromFormat('Y/m/d', $date);
$dateTime->add(DateInterval::createFromDateString($weeks . ' weeks'));
$dateTime->modify('next monday');
// Output the new date.
echo $dateTime->format('Y-m-d');
References:
DateTime.
DateTime::createFromFormat
DateTime::add
DateTime::modify
DateInterval::createFromDateString
DateTime::format
Are you looking for something like this?
$today = time();
$weeks = 2;
// timestamp 2 weeks from now
$futureWeeks = strtotime("+ ".$weeks." weeks");
// the next monday after the timestamp date
$futureMonday = strtotime("next monday",$futureWeeks);
echo date("Y-m-d", $futureMonday);
// or in one line
echo date("Y-m-d", strtotime("next monday", strtotime("+ ".$weeks." weeks")));
PHP is using an unix timestamp for date calculations. Functions as date() and strtotime() using a timestamp as an optional second parameter. This is used a reference for formatting and calculations. If no timestamp is passed to the function the current timestamp is used (time()).
I have the answer here. This will show the next wednesday every 2 weeks and the first date to start from would be the 10th.
I have also added in an estimated delivery which would be 6 weeks after that date.
We will be placing our next order for this on:
<?php
$date = '2020/05/26';
$weeks = 2;
$dateTime = DateTime::createFromFormat('Y/m/d', $date);
$dateTime->add(DateInterval::createFromDateString($weeks . ' weeks'));
$dateTime->modify('wednesday');
echo $dateTime->format('d/m/Y');
?>
Expected delivery for the next order will be:
<?php
$date = '2020/05/26';
$weeks = 2;
$dateTime = DateTime::createFromFormat('Y/m/d', $date);
$dateTime->add(DateInterval::createFromDateString($weeks . ' weeks'));
$dateTime->modify('+42 days next wednesday');
echo $dateTime->format('d/m/Y');
?>
If anyone can confirm this is correct that would be great.
There is a simple way to get unix time range of a day if given a random timestamp from that day ?
I have a date like 1345547471 which is "Tue, 21 Aug 2012 11:11:11 GMT"
There is a php function that can receive a timestamp like this and return a 00:00 hours timestamp and a 23:59 hours timestamp of that day ?
Thank you.
Sure, DateTime can do that:
$time = 1345547471;
$date = new DateTime;
// $date->setTimezone( new DateTimeZone( "America/New_York")); // Can set TZ here if needed
$date->setTimestamp( $time);
Now, you can set the time to whatever you want:
$date->setTime( 0, 0, 0); // 0h 0m 0s
And grab the resulting UNIX Timestamp:
$timestamp = $date->getTimestamp();
Same thing for the next use-case:
$date->setTime( 23, 59, 0);
$timestamp = $date->getTimestamp();
It is important to note that DateTime will properly handle cases of daylight savings time and local time discontinuities.
You can use the mod (gives the remainder after a division) PHP function like this to get the first second of a Unix timestamp (ie, today 0:00:00)
$var=time()-(time()%86400);
Then with this unix timstamp, you can add 86399 to get the last second of the day.
Edit: This doesn't account for dalylight savings.
$ts = 1345547471;
$ts_00_00 = mktime(0,0,0, date("m", $ts), date("d",$ts), date("Y",$ts);
$ts_23_59 = mktime(23,59,59, date("m", $ts), date("d",$ts), date("Y",$ts);
Documentation:
http://php.net/manual/en/function.date.php
http://php.net/manual/en/function.mktime.php
If you are using PHP >= 5.3.0 Then you can use this...
Check out for this.
http://www.php.net/manual/en/datetime.createfromformat.php
This is similar to Fluffeh's answer, but accounts for daylight savings time. This is based on the server's time zone.
//Get time range for today
$start = strtotime(date("Y-m-d")." 00:00:00");
$end = strtotime(date("Y-m-d")." 23:59:59");
//Show our date in a human-readable format for troubleshooting
echo date(DATE_RFC1036,$start)."<br>".date(DATE_RFC1036,$end);
If you want to specify a custom timezone instead of the server timezine, you can add it to like so:
//Get time range for today
$start = strtotime(date("Y-m-d")." 00:00:00 -0500");
$end = strtotime(date("Y-m-d")." 23:59:59 -0500");
//Show our date in a human-readable format for troubleshooting
echo date(DATE_RFC1036,$start)."<br>".date(DATE_RFC1036,$end);
Link to working Sample
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.