here is my code
function check($dt) {
$date = date("Y-m-d");
$start = new DateTime($date);
$end = new DateTime($dt);
$diff = $start->diff( $end );
return $diff->format( '%d days' );
}
print check('2009-12-14');
that prints 29 days
where am i wrong ?
It's explained in the manual:
<?php
$january = new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval = $february->diff($january);
// %a will output the total number of days.
echo $interval->format('%a total days')."\n";
// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');
?>
You want:
function check($dt) {
$date = date("Y-m-d");
$start = new DateTime($date);
$end = new DateTime($dt);
$diff = $start->diff( $end );
return $diff->format( '%a days' );
}
print check('2009-12-14');
gives 180 days.
Related
How to include the startdate as well. When you count days it omits the first day, but i want to include the first day as well.
$d1 = '2018-02-01 00:00:00';
$d2 = '2018-02-05 00:00:00';
function timeDifference($dT1, $dT2){
$d1 = new DateTime($dT1);
$d2 = new DateTime($dT2);
$d = $d1->diff($d2);
$total = $d->days;
$month = $d->m.' months';
$days = $d->d.' days';
if ($total > 30) {
$returnDate = $month.' '.$days;
}
else {
$returnDate = $days;
}
return $returnDate;
}
echo timeDifference($d1, $d2); // 4 (i want 5)
Well, the difference between the 01. and 05. is four days, it's not ignoring anything. Why don't you do it like that?
€dit: Please note that this can still go wrong for a date difference which will exceed a month (e.g. 30 days +1 = 31, but the month only has 30 days...)
<?PHP
$d1 = '2018-02-01 00:00:00';
$d2 = '2018-02-05 00:00:00';
function timeDifference($dT1, $dT2){
$d1 = new DateTime($dT1);
$d2 = new DateTime($dT2);
$d = $d1->diff($d2);
$total = $d->days;
$month = $d->m.' months';
$dayDifference = $d->d;
if($dayDifference !== 0)
{
$dayDifference++;
}
$days = $dayDifference.' days';
if ($total > 30) {
$returnDate = $month.' '.$days;
}
else {
$returnDate = $days;
}
return $returnDate;
}
echo timeDifference($d1, $d2);
?>
2:
<?PHP
$d1 = '2018-02-01 00:00:00';
$d2 = '2018-02-05 00:00:00';
function timeDifference($dT1, $dT2){
$d1 = new DateTime($dT1);
$d1->sub(new DateInterval("P1D"));
$d2 = new DateTime($dT2);
$d = $d1->diff($d2);
$total = $d->days;
$month = $d->m.' months';
$days = $d->d.' days';
if ($total > 30) {
$returnDate = $month.' '.$days;
}
else {
$returnDate = $days;
}
return $returnDate;
}
echo timeDifference($d1, $d2);
?>
The function works as expected. Between date 2018-02-01 00:00:00 and date 2018-02-05 00:00:00 there are effectively 4 days (01, 02, 03, 04). The fifth is not counted because the date 2018-02-05 00:00:00 is considered as the upper limit.
If you wish your function returns 5 instead of 4, make the increment inside it or make the right hand side input date 2018-02-06 00:00:00.
Hello guys i am working in php and my requirement is to get complete week dates from given date as i need to calculate weekly working hour. And week must be started from sunday to saturday not monday to sunday. I have code which works properly for other days of week except sunday. it means if give any dates from monday to saturday it works properly but if i give sunday's date it give last week's dates. please check my code and advise me for better solution.
$days = array();
$ddate = "2018-01-07";
$date = new DateTime($ddate);
$week = $date->format("W");
$y = date("Y", strtotime($ddate));
echo "Weeknummer: $week"."<br>";
echo "Year: $y"."<br>";
for($day=0; $day<=6; $day++)
{
$days[$day] = date('Y-m-d', strtotime($y."W".$week.$day))."<br>";
}
print_r($days);
Using the DateTime, DateInterval and DatePeriod classes you could do it like this perhaps
function getperiod( $start ){
return new DatePeriod(
new DateTime( $start ),
new DateInterval('P1D'),
new DateTime( date( DATE_COOKIE, strtotime( $start . '+ 7days' ) ) )
);
}
$start='2018-01-07';
$period=getperiod( $start );
foreach( $period as $date ){
echo $date->format('l -> Y-m-d') . '<br />';
}
Which returns
Sunday -> 2018-01-07
Monday -> 2018-01-08
Tuesday -> 2018-01-09
Wednesday -> 2018-01-10
Thursday -> 2018-01-11
Friday -> 2018-01-12
Saturday -> 2018-01-13
Or, by modifying the parameters of the getperiod function you can make that function far more flexible.
function getperiod( $start, $interval='P1D', $days=7 ){
return new DatePeriod(
new DateTime( $start ),
new DateInterval( $interval ),
new DateTime( date( DATE_COOKIE, strtotime( $start . '+ '.$days.' days' ) ) )
);
}
$start='2018-01-07';
$days=array();
$period=getperiod( $start );
foreach( $period as $date ){
$days[]=$date->format('Y-m-d');
}
echo '<pre>',print_r($days,true),'</pre>';
For instance: To find every Sunday for the next year
$period=getperiod( $start,'P7D', 365 );
foreach( $period as $date ){
$days[]=$date->format('Y-m-d');
}
echo '<pre>',print_r($days,true),'</pre>';
To ensure that the calculations begin on a Sunday which has a numeric value of 7
function getperiod( $start, $interval='P1D', $days=7 ){
return new DatePeriod(
new DateTime( $start ),
new DateInterval( $interval ),
new DateTime( date( DATE_COOKIE, strtotime( $start . '+ '.$days.' days' ) ) )
);
}
/* A date from which to begin calculations */
$start='2018-01-01';
/* Array to store output */
$days=array();
/* integer to represent which day of the week to operate upon */
$startday = 7;
/* Output format for resultant dates */
$output='Y-m-d';
/* Calculate initial startdate given above variables */
$start=date( DATE_COOKIE, strtotime( $start . ' + ' . ( $startday - date( 'N', strtotime( $start ) ) ) . ' days' ) );
/* Get the period range */
$period=getperiod( $start );
foreach( $period as $date ){
/* store output in desired format */
$days[]=$date->format( $output );
}
/* do something with data */
echo '<pre>',print_r($days,true),'</pre>';
From source,
Here is the snippet you are looking for,
// set current date
$date = '01/03/2018';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400){
print date("m/d/Y l", $ts) . "\n";
}
Here is working demo.
If you need normal standard format code,
Here is your snippet,
// set current date
$date = '2018-01-03';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset * 86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400) {
print date("Y-m-d l", $ts) . "\n";
}
Here is working demo.
EDIT
As per your requirement, now week will start from sunday to saturday
<?php
// set current date
$date = '2018-01-03';
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Sunday
$dow = date('w', $ts);
$offset = $dow;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Sunday
$ts = $ts - $offset * 86400;
// loop from Sunday till Saturday
for ($i = 0; $i < 7; $i++, $ts += 86400) {
print date("Y-m-d l", $ts) . "\n";
}
<?php
$days = array();
$ddate = "2018-01-07";
$y = date("Y", strtotime($ddate));
if(date("l", strtotime($ddate))=='Sunday'){
$ddate = date("Y-m-d ", strtotime($ddate. "+1 day"));
}
$date = new DateTime($ddate);
$week = $date->format("W");
echo "<br/>";
echo "Weeknummer: $week"."<br>";
echo "Year: $y"."<br>";
for($day=0; $day<=6; $day++)
{
$days[$day] = date('Y-m-d', strtotime($y."W".$week.$day))."<br>";
}
print_r($days);
?>
try this:
$days = array();
$ddate = "2018-01-07";
$date = new DateTime($ddate);
$week = $date->format("N")==7?$date->modify("+1 week")->format("W"):$date->format("W");
$y = date("Y", strtotime($ddate));
echo "Weeknummer: $week"."<br>";
echo "Year: $y"."<br>";
for($day=0; $day<=6; $day++)
{
$days[$day] = date('Y-m-d', strtotime($y."W".$week.$day))."<br>";
}
print_r($days);
$dto = new DateTime();
$year = date_create($this->week_date)->format('o');
$week_no = date('W', strtotime($this->week_date));
$dto->setISODate($year, $week_no);
$dto->modify('-1 days');
$ret['sunday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['monday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['tuesday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['wednesday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['thursday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['friday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['saturday'] = $dto->format('Y-m-d');
$dto->modify('+1 days');
$ret['next_sunday'] = $dto->format('Y-m-d');
I have the following code:
<?php
function cuantosdias($d){
$d = strtotime($d);
$c = strtotime("now");
$e = $c - $d;
return $e;
};
$fecha = "13-10-2016 00:00:00";
$cant = cuantosdias($fecha);
echo $cant/86400 . "\n";
I get the days between 2 dates.
I wonder how can I get $cant in format:d H:i:s.
Is there a function to do that?
Simply, you can try this way:
<?php
$fecha = "13-10-2016 00:00:00";
function dateDifference($date, $differenceFormat = '%y year(s) %m month(s) %d day(s) %H:%i:%s' )
{
$datetime1 = date_create($date);
$datetime2 = date_create();
$interval = date_diff($datetime1, $datetime2);
return $interval->format($differenceFormat);
}
echo dateDifference($fecha);
I have as unix timestamps
$now = strtotime("2013-12-10");
$start_date = strtotime("2013-01-01");
$end_date = strtotime("2013-12-31");
The $start date and $end date span a period of time and the $now timestamp sits in the middle of the two.
I also have a variable date interval like so:
$interval = new DateInterval('P1W');
// or
$interval = new DateInterval('P3D');
Given the above how do I get the start and end timestamps of the interval that now sits in?
The $now, $start_date, $end_date and the interval will be dynamic.
Example
Lets say I have these parameters:
$start_date = '2013-01-01 00:00:00';
$end_date = '2013-12-31 23:59:59';
$now = '2013-12-10 15:45:34';
$interval = new DateInterval( 'P1W' );
I want to know the start and end date of the interval $now sits in. The output I would expect from the above params is:
$int_start_date = '2013-12-10 00:00:00';
$int_end_date = '2013-12-16 23:59:59';
I think this is a less hacky and cleaner approach than yours.
$start_date = new DateTime( '2013-01-01 00:00:00' );
$end_date = new DateTime( '2013-12-31 23:59:59' );
$end_date_ts = $end_date->getTimestamp();
$now = new DateTime( '2013-12-10 15:45:34' );
$now_ts = $now->getTimestamp();
$interval = new DateInterval( 'P1W' );
$periods = new DatePeriod( $start_date, $interval, $end_date );
/** #var \DateTime $period */
foreach($periods as $period){
$periodEnd = clone $period;
$periodEnd->add($interval);
if($period < $now && $now < $periodEnd){
$result = iterator_to_array(new \DatePeriod($period, $interval, $periodEnd->add($interval)));
$int_start_date = $result[0];
$int_end_date = $result[1];
break;
}
}
/** #var DateTime $int_start_date */
/** #var DateTime $int_end_date */
var_dump( $int_start_date->format( 'Y-m-d H:i:s' ) );
var_dump( $int_end_date->modify( '-1 Second' )->format( 'Y-m-d H:i:s' ) );
I have figured the problem myself however is hacky
$start_date = new DateTime( '2013-01-01 00:00:00' );
$end_date = new DateTime( '2013-12-31 23:59:59' );
$end_date_ts = $end_date->getTimestamp();
$now = new DateTime( '2013-12-10 15:45:34' );
$now_ts = $now->getTimestamp();
$interval = new DateInterval( 'P1W' );
$period = new DatePeriod( $start_date, $interval, $end_date );
$intervals = array();
foreach ( $period as $dt ) {
$intervals[] = $dt->getTimestamp();
}
$intervals[] = $end_date_ts;
$int_start_date = new DateTime();
$int_end_date = new DateTime();
for ( $i = 0; $i < count( $intervals ); $i++ ) {
if ( $now_ts >= $intervals[$i] && $now_ts <= $intervals[$i+1]) {
$int_start_date->setTimestamp($intervals[$i]);
$int_end_date->setTimestamp($intervals[$i+1]-1);
break;
}
}
var_dump( $int_start_date->format( 'Y-m-d H:i:s' ) );
var_dump( $int_end_date->format( 'Y-m-d H:i:s' ) );
I gladly accept better approaches if anyone has them.
You could try:
$now = time();
$interval = new DateInterval('P1W');
$interval_seconds = $interval->s + ($interval->i * 60) + ($interval->h * 60 * 60) + ($interval->d * 60 * 60 * 24);
$half_interval = round($interval_seconds / 2);
// Unix timestamps
$interval_start = $now - $half_interval;
$interval_end = $now + $half_interval;
EDIT: 2nd answer following on from comments
This only works for intervals of length 1 - eg 1 week, 1 year etc.
If your interval is > 1 then you'll need to somehow determine how far through the interval you are... e.g for a 2 week interval, are you in the first week or the second week?
$now = time();
$interval = "week";
switch ($interval) {
case "year":
$start_int = strtotime(date("Y", $now)."-01-01 00:00:00");
$end_int = strtotime(date("Y", $now)."-12-31 23:59:59");
break;
case "month":
$start_int = strtotime(date("Y-m", $now)."-01 00:00:00");
$end_int = strtotime(date("Y-m-t", $now)." 23:59:59");
break;
case "week":
$start_week = date("Y-m-d", strtotime("previous Monday", $now));
$end_week = date("Y-m-d", strtotime("next Sunday", $now));
$start_int = strtotime($start_week." 00:00:00");
$end_int = strtotime($end_week." 23:59:59");
break;
case "day":
$start_int = strtotime(date("Y-m-d", $now)." 00:00:00");
$end_int = strtotime(date("Y-m-d", $now)." 23:59:59");
break;
case "hour":
$start_int = strtotime(date("Y-m-d H", $now).":00:00");
$end_int = strtotime(date("Y-m-d H", $now).":59:59");
break;
case "minute":
$start_int = strtotime(date("Y-m-d H:i", $now).":00");
$end_int = strtotime(date("Y-m-d H:i", $now).":59");
break;
}
echo date("Y-m-d H:i:s", $start_int), "<br>";
echo date("Y-m-d H:i:s", $end_int), "<br>";
Update 3
I've put the logic from your answer into a single loop:
$start_date = new DateTime( '2013-01-01 00:00:00' );
$end_date = new DateTime( '2013-12-31 23:59:59' );
$end_date_ts = $end_date->getTimestamp();
$now = new DateTime( '2013-12-10 15:45:34' );
$now_ts = $now->getTimestamp();
$interval = new DateInterval( 'P1W' );
$period = new DatePeriod( $start_date, $interval, $end_date );
$int_start_date = $start_date;
$int_end_date = $end_date;
foreach ( $period as $dt ) {
$timestamp = $dt->getTimestamp();
if ($now_ts >= $timestamp) {
$int_start_date->setTimestamp($timestamp);
}
if ($now_ts < $timestamp and $timestamp < $int_end_date->getTimestamp()) {
$int_end_date->setTimestamp($timestamp - 1);
}
}
var_dump( $int_start_date->format( 'Y-m-d H:i:s' ) );
var_dump( $int_end_date->format( 'Y-m-d H:i:s' ) );
if
$_POST['SelectedDate1'] = 2013/08/05
and
$_POST['SelectedDate2'] = 2013/08/07
How can I set a variable which gives me back the number of days (2 in this case) to then echo it as result
I'm looking for a solution that can cover any calendar combination.
Is there any global function in php.
I think, in the following Documentation on PHP.net is exactly what you're trying to do.
http://nl3.php.net/manual/en/datetime.diff.php
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
In your case:
<?php
$first = new DateTime($_POST['SelectedDate1']);
$second = new DateTime($_POST['SelectedDate2']);
$passed = $first->diff($second);
var_dump($passed->format('%R%a days'));
For more formats, next to %R%a, see: http://nl3.php.net/manual/en/function.date.php
<?php
$days = (strtotime($_POST['SelectedDate2']) - strtotime($_POST['SelectedDate1'])) / 86400;
example:
<?php
$_POST['SelectedDate1'] = '2013/08/05' ;
$_POST['SelectedDate2'] = '2013/08/07' ;
$days = (strtotime($_POST['SelectedDate2']) - strtotime($_POST['SelectedDate1'])) / 86400;
var_export($days);
// output: 2
I use this function that I've found on this forum but I don't remember where :
function createDateRangeArray($start, $end) {
// Modified by JJ Geewax
$range = array();
if (is_string($start) === true) $start = strtotime($start);
if (is_string($end) === true ) $end = strtotime($end);
if ($start > $end) return createDateRangeArray($end, $start);
do {
$range[] = date('Y-m-d', $start);
$start = strtotime("+ 1 day", $start);
}
while($start <= $end);
return $range;
}
it returns a range of date as an array, then you just have to get the count
DateTime class is created for this:
$date1 = new DateTime('2013/08/05');
$date2 = new DateTime('2013/08/07');
$diff = $date1->diff($date2);
echo $diff->days;