I'm trying to find the nth day of the month in a timestamp like so:
$day = 15;
$date = new DateTime('#' . $timestamp);
$date->modify($day . ' day of current month');
This generates an error:
Warning: DateTime::modify(): Failed to parse time string (15 day of current month) at position 7
I've also tried "day 15 of current month" and that does not work.
How can I modify my "modify" to find the nth day of the current month in the timestamp?
First retrieve the first day of the month, then add the number of days you want.
$date = new DateTime('first day of ' . date("Y-m-d", $timestamp));
$date->modify('+' . ($day-1) . 'days');
You can use php's date() formatting capabilities with a hard-set "day" value (adapt as necessary):
<?php
$timestamp = time();
$format = date('Y-15-M', $timestamp);
$fifteenth = strtotime($format);
echo "15th was a " . date("D", $fifteenth) . "\n";
Related
I have a date set using PHP datetime like this..
$originaldate = 2019-01-10 17:52:17
$converted = DateTime::createFromFormat("Y-m-d H:i:s", $originaldate);
The date is successfuly converted into a PHP DateTime object, now I am trying to add create 2 new dates that are 6 months and 1 year ahead of this date.
Whats the best way to achieve this?
You should look into php class DateInterval http://php.net/manual/en/class.dateinterval.php
Here's an example:
$converted = DateTime::createFromFormat("Y-m-d H:i:s", $originaldate);
$converted1Year = $converted->add(new DateInterval("P1Y"));//add one year //object reference is the same so adding a year altered original object and a reference to it is passed back, not copied
$converted2 = DateTime::createFromFormat("Y-m-d H:i:s", $originaldate);
$converted6months = $converted2->add(new DateInterval("P6M")); // add 6 months
And as suggested in the comments here's the DateTimeImmutable equivalent:
$converted = DateTimeImmutable::createFromFormat("Y-m-d H:i:s", $originaldate);
$converted1Year = $converted->add(new DateInterval("P1Y"));
$converted6Months = $converted->add(new DateInterval("P6M"));
Check out DateTime::add
$converted->add(new DateInterval("P18M")); // add 18 months
P18M means 18 month interval
You can clone the time to create a duplicate and use DateTime::modify to change the new date.
Try this;
$sixMonths = clone $converted;
$sixMonths->modify('+6 months');
$oneYear = clone $converted;
$oneYear->modify('+1 year');
$converted = $converted->modify('+6 months');
$converted = $converted->modify('+1 year');
Like so:
$sixMonths = date('Y-m-d', strtotime($converted. ' + 6 months'));
$oneYear = date('Y-m-d', strtotime($converted. ' + 1 year'));
The format already default ("Y-m-d H:i:s"). You don't need to use CreateFromFormat, unless you are handle data from 3rd party. My suggestion for the code would be like this
$originaldate = '2019-01-10 17:52:17';
$converted = new DateTime( $originaldate ); //prefer like this
//DateTime::createFromFormat("Y-m-d H:i:s", $originaldate); //after browsing this is recomended
$date6Month = new DateTime( $originaldate );
$date1Year = new DateTime( $originaldate );
$dateBack = new DateTime( $originaldate );
//$date6Month = $date1Year = $dateBack= $converted;
//prefer to use different variable for every date. Not copy
echo "ori:".$converted ->format('Y-m-d H:i:s') . "\n";
//ori:2019-01-10 17:52:17
##6 month later
$date6Month ->add(new DateInterval('P6M'));
echo "6 month:".$date6Month ->format('Y-m-d H:i:s') . "\n";
//6 month:2019-07-10 17:52:17
##1 year later
$date1Year ->add(new DateInterval('P1Y'));
echo "1 year:".$date1Year ->format('Y-m-d H:i:s') . "\n";
//1 year:2020-01-10 17:52:17
//1 year:2020-07-10 17:52:17 (wrong if using copy main parameter)
$date1Year ->add( DateInterval::createFromDateString('1 Years') );
echo "1 year (later):".$date1Year ->format('Y-m-d H:i:s') . "\n";
//1 year (later):2021-01-10 17:52:17
//1 year (later):2021-07-10 17:52:17 (wrong if using copy main parameter)
you can use DateInterval::createFromDateString for readable code than using format. My suggestion is to separated the variable not copy from the origin.
The format you can use on DateInterval
Start "P" when contain Day, Month and Year
Format
Info
Example
Y
Year
1Y
M
Month
3M
D
Day
5D
example: P1Y3M5D
Always Start "P" before "T" if not contain Day, Month and Year (PT1H). If not start it with "T"
Format
Info
Example
H
HOUR
1H
M
MINUTES
3M
S
SECONDS
5S
F
MICROSECOND (php7+)
5F
example: PT1H3M5S
wrong: T1H3M5S
other example (from link below)
date_default_timezone_set('America/Phoenix');
//is important to add when your time are detail
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->format('Y-m-d H:i:s') . "\n";
//2007-06-05 04:03:02
$originaldate = 2019-01-10 17:52:17
$dateBack = $dateBack2 = new DateTime( $originaldate );
//if you want to substract the value you can use this
$dateBack ->sub(new DateInterval('P1Y2M3DT1H4M1S'));
echo $dateBack ->format('Y-m-d H:i:s') . "\n";
//output: 2019-05-07 16:48:16
$dateBack2=$converted;
$formatDay='P1Y3M6D'; //only year, month and day
$formatTime='T1H3M6S'; //only hour, minutes and seconds
$dateBack2 ->sub(new DateInterval( $formatDay.$formatTime ));
echo $dateBack ->format('Y-m-d H:i:s') . "\n";
//2018-02-01 15:45:10
as mention on the phpmanual, there is other format (microtime) that's not include on this example.
related link
Date Time PHP
Date Interval
Format on Interval
Date Interval create using String
I want to find the next occurrence of date from the current date.
For example, imagine I want to find 20th of the month from current date
If current date is 10th october then return the result 2014-10-20 (Y-m-d)
If current date is 22nd october then return the result 2014-11-20 (Y-m-d)
I created a solution just now using a while loop.
$oldd= "2014-06-20";
$newdate = date("Y-m-d",strtotime($oldd."+1months"));
while(strtotime($newdate) <= strtotime(date("Y-m-d")))
{
$newdate = date("Y-m-d",strtotime($newdate."+1months"));
}
echo $newdate;
manually and pass that to strtotime(). The time information you need to extract from the reference time string. Like this:
$refdate = '2014-02-25 10:30:00';
$timestamp = strtotime($refdate);
echo date('Y-m-d H:i:s',
strtotime("next Thursday " . date('H:i:s', $timestamp), $timestamp)
);
same results could be achieved using string concatenation:
echo date('Y-m-d', strtotime("next Thursday", $timestamp)
. ' ' . date('H:i:s', $timestamp);
another way, you can use methods of DateTime object, PHP has really rich API in dealing with date time.
$current_date = new DateTime('2014-06-20');
if ($current_date->format('d') >= 20) {
// $current_date->modify('last day of this month')->modify("+20 days");
$current_date->modify('first day of next month')->modify("+19 days");
}else{
$current_date->modify('first day of this month')->modify("+19 days");
}
echo $current_date->format("Y-m-d");
http://php.net/manual/en/datetime.modify.php
http://php.net/manual/en/datetime.formats.relative.php
I'm trying to get the date from the week number, day number and year.
For eg:
week number = 52
day number = 4 (of week 52)
year = 2013
In this case, the date should be 26-12-2013.
How can I do it using PHP? I've already tried with strtotime(), but I'm confused about the formats. Can someone help?
Make use of setISODate()
<?php
$gendate = new DateTime();
$gendate->setISODate(2013,52,4); //year , week num , day
echo $gendate->format('d-m-Y'); //"prints" 26-12-2013
Try this code.
<?php
function change_date($week_num, $day) {
$timestamp = strtotime(date('Y') . '-W' . $week_num . '-' . $day);
return $timestamp;
}
$timestamp = change_date(52, 4);
echo date('d-m-Y', $timestamp);
?>
You can also use the strtotime function. In your example, you can write:
date("Y-m-d", strtotime("Y2013W52-4")) // outputs: 2013-12-26
The strtotime will give you a timestamp that you can use in combination withe the date function.
all
Decrease month by one in strtotime in this loop.
$twitter_val7 .='{
date: new Date('.date("Y",strtotime($date)).', '.date("m",strtotime($date)).', '.date("d",strtotime($date)).'),
value: '.$result_twitter->counts.'
},';
To decrease by 1 month using strtotime() you literally tell it to decrease by one month:
strtotime($date . ' - 1 month');
Assuming, of course, that $date is a format strtotime() understands.
I would do it like this .. i guess $date would go in place of '2000-01-01':
$initial = new DateTime('2000-01-01');
$interval = new DateInterval('P1M');
$newdate = $initial->sub( $interval );
echo $newdate->format('Y-m-d H:i:s');
To decrease month by using strtotime
$date='2014-09-03';
$numMonth=1;//here you can pass no. of month
$resultDate=date('Y-m-d',strtotime($date . " - $numMonth month"));
I have a date returned as part of a MySQL query in the form 2010-09-17.
I would like to set the variables $Date2 to $Date5 as follows:
$Date2 = $Date + 1
$Date3 = $Date + 2
etc., so that it returns 2010-09-18, 2010-09-19, etc.
I have tried
date('Y-m-d', strtotime($Date. ' + 1 day'))
but this gives me the date before $Date.
What is the correct way to get my Dates in the format form 'Y-m-d' so that they may be used in another query?
All you have to do is use days instead of day like this:
<?php
$Date = "2010-09-17";
echo date('Y-m-d', strtotime($Date. ' + 1 days'));
echo date('Y-m-d', strtotime($Date. ' + 2 days'));
?>
And it outputs correctly:
2010-09-18
2010-09-19
If you're using PHP 5.3, you can use a DateTime object and its add method:
$Date1 = '2010-09-17';
$date = new DateTime($Date1);
$date->add(new DateInterval('P1D')); // P1D means a period of 1 day
$Date2 = $date->format('Y-m-d');
Take a look at the DateInterval constructor manual page to see how to construct other periods to add to your date (2 days would be 'P2D', 3 would be 'P3D', and so on).
Without PHP 5.3, you should be able to use strtotime the way you did it (I've tested it and it works in both 5.1.6 and 5.2.10):
$Date1 = '2010-09-17';
$Date2 = date('Y-m-d', strtotime($Date1 . " + 1 day"));
// var_dump($Date2) returns "2010-09-18"
From PHP 5.2 on you can use modify with a DateTime object:
http://php.net/manual/en/datetime.modify.php
$Date1 = '2010-09-17';
$date = new DateTime($Date1);
$date->modify('+1 day');
$Date2 = $date->format('Y-m-d');
Be careful when adding months... (and to a lesser extent, years)
Here is a small snippet to demonstrate the date modifications:
$date = date("Y-m-d");
//increment 2 days
$mod_date = strtotime($date."+ 2 days");
echo date("Y-m-d",$mod_date) . "\n";
//decrement 2 days
$mod_date = strtotime($date."- 2 days");
echo date("Y-m-d",$mod_date) . "\n";
//increment 1 month
$mod_date = strtotime($date."+ 1 months");
echo date("Y-m-d",$mod_date) . "\n";
//increment 1 year
$mod_date = strtotime($date."+ 1 years");
echo date("Y-m-d",$mod_date) . "\n";
You can also use the following format
strtotime("-3 days", time());
strtotime("+1 day", strtotime($date));
You can stack changes this way:
strtotime("+1 day", strtotime("+1 year", strtotime($date)));
Note the difference between this approach and the one in other answers: instead of concatenating the values +1 day and <timestamp>, you can just pass in the timestamp as the second parameter of strtotime.
Here has an easy way to solve this.
<?php
$date = "2015-11-17";
echo date('Y-m-d', strtotime($date. ' + 5 days'));
?>
Output will be:
2015-11-22
Solution has found from here - How to Add Days to Date in PHP
Using a variable for Number of days
$myDate = "2014-01-16";
$nDays = 16;
$newDate = strtotime($myDate . '+ '.$nDays.' days');
echo new Date('d/m/Y', $newDate); //format new date
Here is the simplest solution to your query
$date=date_create("2013-03-15"); // or your date string
date_add($date,date_interval_create_from_date_string("40 days"));// add number of days
echo date_format($date,"Y-m-d"); //set date format of the result
This works. You can use it for days, months, seconds and reformat the date as you require
public function reformatDate($date, $difference_str, $return_format)
{
return date($return_format, strtotime($date. ' ' . $difference_str));
}
Examples
echo $this->reformatDate('2021-10-8', '+ 15 minutes', 'Y-m-d H:i:s');
echo $this->reformatDate('2021-10-8', '+ 1 hour', 'Y-m-d H:i:s');
echo $this->reformatDate('2021-10-8', '+ 1 day', 'Y-m-d H:i:s');
To add a certain number of days to a date, use the following function.
function add_days_to_date($date1,$number_of_days){
/*
//$date1 is a string representing a date such as '2021-04-17 14:34:05'
//$date1 =date('Y-m-d H:i:s');
// function date without a secrod argument returns the current datetime as a string in the specified format
*/
$str =' + '. $number_of_days. ' days';
$date2= date('Y-m-d H:i:s', strtotime($date1. $str));
return $date2; //$date2 is a string
}//[end function]
All have to use bellow code:
$nday = time() + ( 24 * 60 * 60);
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Day: '. date('Y-m-d', $nday) ."\n";
Another option is to convert your date string into a timestamp and then add the appropriate number of seconds to it.
$datetime_string = '2022-05-12 12:56:45';
$days_to_add = 1;
$new_timestamp = strtotime($datetime_string) + ($days_to_add * 60 * 60 * 24);
After which, you can use one of PHP's various date functions to turn the timestamp into a date object or format it into a human-readable string.
$new_datetime_string = date('Y-m-d H:i:s', $new_timestamp);