Add a year to a date in string format using php - php

I have a date in a string format such as string(10) "30/08/2014" and i need to add a year to it. In my case i'll have 30/08/2015 I was trying to use something like this but i am failing...
$start = new DateTime($details['start_date']);
$start->add(new DateInterval('P1Y'));
$end_date = $start;
any suggestion please? thank you!
The error i get now is "DateTime::__construct(): Failed to parse time string (30/08/2014) at position 0 (3): Unexpected character"
Do I have to format the string such as Y-m-d or there is a fastest and more efficient way?

This might do the trick for you.
$end_date = strtotime(date($details['start_date'])." + 1 year");
strtotime function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp.

Yes you can add one year to that date. Example:
// you have to define the format of the date that you're feeding
$start = DateTime::createFromFormat('d/m/Y', '30/08/2014'); // create format first ($details['start_date'])
// then use the method ->add() and feed it with a DateInterval Object with the proper interval
$start->add(new DateInterval('P1Y')); // add the year
$end = $start->format('d/m/Y'); // assign it to a variable
echo $end; // 30/08/2015

convert date in Y-m-d format
$var = '20/04/2012';
$date = str_replace('/', '-', $var);
$new_date = date('Y-m-d', strtotime("+1 year", strtotime($date)));
As, PHP doesn't work well with dd/mm/yyyy format.
I hope this will help you.

$date = '25/05/2010';
$date = str_replace('/', '-', $date);
echo date('Y-m-d', strtotime("+1 year", strtotime($date)));
Result:
2010-05-25
The strtotime documentation reads:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator
between the various components: if the separator is a slash (/), then the
American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.),
then the European d-m-y format is assumed.

Related

Sum date using strtotime always returns 01/01/1970

I am trying to add 1 day to a date using strtotime but I canĀ“t get it to work. It always returns 02/01/1970
$date = date ("d/m/Y H:i:s", filemtime($directory));
$newdate = date("d/m/Y", strtotime($date));
$tomorrow = date('d/m/Y',strtotime($newdate . "+1 days"));
echo $tomorrow; //Always return 02/01/1970
Because strtotime() differentiates between USA date format and Sensible date format by looking at the date seperator all you need to do is us the - seperator if you want to use the sensible date format, like this, in your intermediate date manipulations
$date = date ("d-m-Y H:i:s", filemtime($directory));
$newdate = date("d-m-Y", strtotime($date));
$tomorrow = date('d/m/Y',strtotime($newdate . "+1 days"));
echo $tomorrow; //Always return 02/01/1970
FROM the manual
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-), the date string is parsed as y-m-d.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
Better work with DateTime():
$date = new DateTime(strtotime(filemtime($directory)));
echo $newdate = $date->format('d/m/Y');
$date->modify('+1 day');
echo $tomorrow = $date->format('d/m/Y');
Output:
20/01/2020
21/01/2020
If your filemtime($directory) returns a string formatted as your date() mask, I mean d/m/Y H:i:s, then you can do next steps:
for example, according to this mask, it looks like:
$s = "02/06/2019 22:23:22";
now you can do strtotime()
$date = date ("d/m/Y H:i:s", strtotime($s));
then transform it to the DateTime object
$st_date = new DateTime($date);
now you can simply modify it as you want
$st_date->modify('+1 days');
to see the result string value use:
$tomorrow = $st_date->format('d/m/Y');
echo 'tomorrow -> '.$tomorrow;
Output:
date->02/06/2019 22:23:22
tomorrow -> 03/06/2019
Demo

Adding x no of days to given date, but it is taking the day number as month and doing the calc. Help me fix the format

I m trying to add 28 days to the given date and echo, however it is taking the given date and considering it as month and adding the days given
Help me fix the format.
my code goes as:
$start = "04/03/2019";
$nextpay1 = date('d/m/Y',strtotime($start . "+28 days"));
echo $nextpay1;
as result it is echoing "01/05/2019", which is not right..
I'll start my answer by quoting the strtotime docs:
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at
the separator between the various components: if the separator is a
slash (/), then the American m/d/y is assumed; whereas if the
separator is a dash (-) or a dot (.), then the European d-m-y format
is assumed. If, however, the year is given in a two digit format and
the separator is a dash (-), the date string is parsed as y-m-d.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD)
dates or DateTime::createFromFormat() when possible.
So, in your case:
$date = DateTime::createFromFormat('d/m/Y', '04/03/2019');
$date->modify('+28 days');
echo $date->format('d/m/Y');
The problem is that $start is being parsed in the default mm/dd/yyyy format. You should use a function to parse it as the format you intend, and then add to that.
$parsed = date_parse_from_format('d/m/Y', $start);
$startdate = mktime(
$parsed['hour'],
$parsed['minute'],
$parsed['second'],
$parsed['month'],
$parsed['day'],
$parsed['year']
);
$nextpay1 = date('d/m/Y', strtotime('+28 days', $startdate));
$date=Date('y:m:d', strtotime("+3 days"));
This will save the date after 3 days

Date format not working correctly

Im submitting a form that has a date range picker in it.
I have the code to get the value of the picker from the form, which is in this format:
01/03/2017 - 01/03/2017
I also have it so that it splits the date range into two variables.
$one = 20/01/2017
$two = 13/03/2017
Im now trying to format the date of these variables into the one that MYSQL uses.
My problem is that the end date will fail and be displayed as 1970-01-01 all the time.
// Get the range from the form
$daterange = $_POST["daterange"];
// Split the range into a start and end date
list($one, $two) = explode("-", "$daterange", 2);
// Test the split worked
echo $one;
echo $two;
// Format the start date into MySQL style
$StartDate = date("Y-m-d", strtotime($one));
// Test date
echo $StartDate;
// Format the end date into MySQL style
$EndDate = date("Y-m-d", strtotime($two));
//Test date
echo $EndDate;
Personnaly, I prefer the date_create_from_format that does not presume anything.
One-liner :
$StartDate = date_create_from_format( "d/m/Y" , $one )->format("Y-m-d");
Try this:
$one = '20/01/2017';
$one = str_replace('/', '-', $one);
echo date('Y-m-d', strtotime($one));
// Output: 2017-01-20
Working Code
For the reason, see The PHP Manual for strtotime() Specifically this note
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
Use this to format your date:
$StartDate = date_format(date_create_from_format('d/m/Y', $one), 'Y-m-d');
To reverse:
$reverse = date('d/m/Y', strtotime($StartDate));

PHP: generating an end date with user specified start date and duration

I am trying to create a function that determines the end date of an advert based on the start date and duration parameter passed by a user.
Example:
If user specify start date as 5th June 2013 and duration as 45 days:
$ad_startdate = '2013-06-05';
$ad_duration = 45;
The function should automatically get the end date which should be 20th July 2013:
$ad_end_date = '2013-07-20';
Pls note that to make it easy to generate the end date, I've assigned the variable for months a constant value which will be 30 days. Whether it's february or november or a leap year, every month has a fixed variable value of 30.
I was trying to come up with something around this but just cant figure it out.
$ad_startdate = '2013-06-05';
$ad_duration = 45;
// End date should be 2013-07-20
function getAdvertEndDate ($ad_startdate, $ad_duration){
//Add up start date with duration
$end_date = strtotime($ad_startdate) + $ad_duration;
return $end_date;
}
I have browsed through SO questions just to see if anyone has something around this but the answered ones are so different from mine challenge.
Would be very grateful getting help with this.
function getAdvertEndDate ($ad_startdate, $ad_duration){
return date("Y-m-d", strtotime($ad_startdate) + ($ad_duration * 86400));
}
Use like so:
$endDate = getAdvertEndDate("2013-04-08", 40);
PHP >= 5.3.0 Object oriented style
$date = DateTime::createFromFormat('Y-m-d', '2013-06-05');
$date->add(new DateInterval('P45D'));
echo $date->format('Y-m-d') . "\n";
Or Procedural style
$date = date_create('2013-06-05');
date_add($date, date_interval_create_from_date_string('45 days'));
echo date_format($date, 'Y-m-d');
Result:
2013-07-20
Code:
function getAdvertEndDate ($ad_startdate, $ad_duration){
$date = DateTime::createFromFormat('Y-m-d', $ad_startdate);
$date->add(new DateInterval('P'.$ad_duration.'D'));
return $date->format('Y-m-d');
}
For PHP < 5.3 use strtotime():
function getAdvertEndDate ($ad_startdate, $ad_duration){
//Add up start date with duration
return date('Y-m-d', strtotime($ad_startdate. " + $ad_duration days"));
}
echo getAdvertEndDate('2013-06-05', '45'); // 2013-07-20
http://www.php.net/manual/en/datetime.add.php
Try this code
$date = '2013-06-05';
$date1 = strtotime($date);
$date2 = strtotime('+45 day',$date1);
echo date('Y-m-d', $date2);
The native strtotime() function does this work.
Use this:
$ad_startdate = '2013-06-05';
$ad_duration = 45;
$dateArray = explode('-', $ad_startdate);
$newDate = date('Y-m-d', strtotime('+ ' . $ad_duration . ' days', mktime(0, 0, 0, $dateArray[1], $dateArray[2], $dateArray[0]));
If you're using strtotime, you cant use the date format you've specified, as if using - seperators, strtotime() expects the format differently.
From PHP.net
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.

Converting string to Date and DateTime

If I have a PHP string in the format of mm-dd-YYYY (for example, 10-16-2003), how do I properly convert that to a Date and then a DateTime in the format of YYYY-mm-dd? The only reason I ask for both Date and DateTime is because I need one in one spot, and the other in a different spot.
Use strtotime() on your first date then date('Y-m-d') to convert it back:
$time = strtotime('10/16/2003');
$newformat = date('Y-m-d',$time);
echo $newformat;
// 2003-10-16
Make note that there is a difference between using forward slash / and hyphen - in the strtotime() function. To quote from php.net:
Dates in the m/d/y or d-m-y formats
are disambiguated by looking at the
separator between the various
components: if the separator is a
slash (/), then the American m/d/y is
assumed; whereas if the separator is a
dash (-) or a dot (.), then the
European d-m-y format is assumed.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
You need to be careful with m/d/Y and m-d-Y formats. PHP considers / to mean m/d/Y and - to mean d-m-Y. I would explicitly describe the input format in this case:
$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');
That way you are not at the whims of a certain interpretation.
To parse the date, you should use:
DateTime::createFromFormat();
Ex:
$dateDE = "16/10/2013";
$dateUS = \DateTime::createFromFormat("d.m.Y", $dateDE)->format("m/d/Y");
However, careful, because this will crash with:
PHP Fatal error: Call to a member function format() on a non-object
You actually need to check that the formatting went fine, first:
$dateDE = "16/10/2013";
$dateObj = \DateTime::createFromFormat("d.m.Y", $dateDE);
if (!$dateObj)
{
throw new \UnexpectedValueException("Could not parse the date: $date");
}
$dateUS = $dateObj->format("m/d/Y");
Now instead of crashing, you will get an exception, which you can catch, propagate, etc.
$dateDE has the wrong format, it should be "16.10.2013";
$d = new DateTime('10-16-2003');
$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16
Edit: you can also pass a DateTimeZone to DateTime() constructor to ensure the creation of the date for the desired time zone, not the server default one.
Since no one mentioned this, here's another way:
$date = date_create_from_format("m-d-Y", "10-16-2003")->format("Y-m-d");
To create a date from any string you can use:
$date = DateTime::createFromFormat('d-m-y H:i', '01-01-01 01:00');
echo $date->format('Y-m-d H:i');
If you have the date formatted as "07/May/2018" and need to make it into "2018-05-07" so that it is MySQL compatible, you can use:
if (!empty($date)) {
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
$date = date('Y-m-d', $timestamp);
}
For first Date
$_firstDate = date("m-d-Y", strtotime($_yourDateString));
For New Date
$_newDate = date("Y-m-d",strtotime($_yourDateString));
If you have format dd-mm-yyyy then in PHP it won't work as expected. In PHP document they have below guideline.
Dates in the m/d/y or d-m-y formats are disambiguated by looking at
the separator between the various components: if the separator is a
slash (/), then the American m/d/y is assumed; whereas if the
separator is a dash (-) or a dot (.), then the European d-m-y format
is assumed.
So, you just can't use as you wish. When your try to use dd/mm/yyyy format with this then it will remove FALSE. You can tweak with the following.
$date = "23/02/2013";
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
echo $timestamp; // prints 1361577600
I try all the above answers, but fail for me where in my case I built a function that get date string with the following format 'YYYY/mm/dd' . so i think much better to explode the string like that:
$old_date = explode('/', $coming_date_str);
$new_data = $old_date[0].'-'.$old_date[1].'-'.$old_date[2]; // this to convert the string as all the above posts and complete
$new_date = date('Y-m-d', strtotime($new_data));
$new_date = DateTime::createFromFormat("Y-m-d", new_date);
It worked for me to do something like:
$stringDate = "2022-02-24T17:15:00";
(if you only send the date "2022-02-24" it fills the time in 00:00:00).
$dateFormat = new DateTime($miStringDate);
If you wish to accept dates using American ordering (month, date, year) for European style formats (using dash or period as day, month, year) while still accepting other formats, you can extend the DateTime class:
/**
* Quietly convert European format to American format
*
* Accepts m-d-Y, m-d-y, m.d.Y, m.d.y, Y-m-d, Y.m.d
* as well as all other built-in formats
*
*/
class CustomDateTime extends DateTime
{
public function __construct(string $time="now", DateTimeZone $timezone = null)
{
// convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y (substr avoids microtime error)
$time = str_replace(['-','.'], '/', substr($time, 0, 10)) . substr($time, 10 );
parent::__construct($time, $timezone);
}
}
// usage:
$date = new CustomDateTime('7-24-2019');
print $date->format('Y-m-d');
// => '2019-07-24'
Or, you can make a function to accept m-d-Y and output Y-m-d:
/**
* Accept dates in various m, d, y formats and return as Y-m-d
*
* Changes PHP's default behaviour for dates with dashes or dots.
* Accepts:
* m-d-y, m-d-Y, Y-m-d,
* m.d.y, m.d.Y, Y.m.d,
* m/d/y, m/d/Y, Y/m/d,
* ... and all other formats natively supported
*
* Unsupported formats or invalid dates will generate an Exception
*
* #see https://www.php.net/manual/en/datetime.formats.date.php PHP formats supported
* #param string $d various representations of date
* #return string Y-m-d or '----' for null or blank
*/
function asYmd($d) {
if(is_null($d) || $d=='') { return '----'; }
// convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y
$d = str_replace(['-','.'], '/', $d);
return (new DateTime($d))->format('Y-m-d');
}
// usage:
<?= asYmd('7-24-2019') ?>
// or
<?php echo asYmd('7-24-2019'); ?>
If you want to get the last day of the current month you can do it with the following code.
$last_day_this_month = date('F jS Y', strtotime(date('F t Y')));

Categories