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

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.

Related

Is there an HTML date time input with format "yyy-mm-dd hh-mm-ss"? [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 1 year ago.
I am trying to convert a date from yyyy-mm-dd to dd-mm-yyyy (but not in SQL); however I don't know how the date function requires a timestamp, and I can't get a timestamp from this string.
How is this possible?
Use strtotime() and date():
$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));
(See the strtotime and date documentation on the PHP site.)
Note that this was a quick solution to the original question. For more extensive conversions, you should really be using the DateTime class to parse and format :-)
If you'd like to avoid the strtotime conversion (for example, strtotime is not being able to parse your input) you can use,
$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('d-m-Y');
Or, equivalently:
$newDateString = date_format(date_create_from_format('Y-m-d', $dateString), 'd-m-Y');
You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.
Or if the source-format always is "Y-m-d" (yyyy-mm-dd), then just use DateTime:
<?php
$source = '2012-07-31';
$date = new DateTime($source);
echo $date->format('d.m.Y'); // 31.07.2012
echo $date->format('d-m-Y'); // 31-07-2012
?>
Use:
implode('-', array_reverse(explode('-', $date)));
Without the date conversion overhead, I am not sure it'll matter much.
$newDate = preg_replace("/(\d+)\D+(\d+)\D+(\d+)/","$3-$2-$1",$originalDate);
This code works for every date format.
You can change the order of replacement variables such $3-$1-$2 due to your old date format.
$timestamp = strtotime(your date variable);
$new_date = date('d-m-Y', $timestamp);
For more, see the documentation for strtotime.
Or even shorter:
$new_date = date('d-m-Y', strtotime(your date variable));
Also another obscure possibility:
$oldDate = '2010-03-20'
$arr = explode('-', $oldDate);
$newDate = $arr[2].'-'.$arr[1].'-'.$arr[0];
I don't know if I would use it but still :)
There are two ways to implement this:
1.
$date = strtotime(date);
$new_date = date('d-m-Y', $date);
2.
$cls_date = new DateTime($date);
echo $cls_date->format('d-m-Y');
Note: Because this post's answer sometimes gets upvoted, I came back
here to kindly ask people not to upvote it anymore. My answer is
ancient, not technically correct, and there are several better
approaches right here. I'm only keeping it here for historical
purposes.
Although the documentation poorly describes the strtotime function,
#rjmunro correctly addressed the issue in his comment: it's in ISO
format date "YYYY-MM-DD".
Also, even though my Date_Converter function might still work, I'd
like to warn that there may be imprecise statements below, so please
do disregard them.
The most voted answer is actually incorrect!
The PHP strtotime manual here states that "The function expects to be given a string containing an English date format". What it actually means is that it expects an American US date format, such as "m-d-Y" or "m/d/Y".
That means that a date provided as "Y-m-d" may get misinterpreted by strtotime. You should provide the date in the expected format.
I wrote a little function to return dates in several formats. Use and modify at will. If anyone does turn that into a class, I'd be glad if that would be shared.
function Date_Converter($date, $locale = "br") {
# Exception
if (is_null($date))
$date = date("m/d/Y H:i:s");
# Let's go ahead and get a string date in case we've
# been given a Unix Time Stamp
if ($locale == "unix")
$date = date("m/d/Y H:i:s", $date);
# Separate Date from Time
$date = explode(" ", $date);
if ($locale == "br") {
# Separate d/m/Y from Date
$date[0] = explode("/", $date[0]);
# Rearrange Date into m/d/Y
$date[0] = $date[0][1] . "/" . $date[0][0] . "/" . $date[0][2];
}
# Return date in all formats
# US
$Return["datetime"]["us"] = implode(" ", $date);
$Return["date"]["us"] = $date[0];
# Universal
$Return["time"] = $date[1];
$Return["unix_datetime"] = strtotime($Return["datetime"]["us"]);
$Return["unix_date"] = strtotime($Return["date"]["us"]);
$Return["getdate"] = getdate($Return["unix_datetime"]);
# BR
$Return["datetime"]["br"] = date("d/m/Y H:i:s", $Return["unix_datetime"]);
$Return["date"]["br"] = date("d/m/Y", $Return["unix_date"]);
# Return
return $Return;
} # End Function
You can try the strftime() function. Simple example: strftime($time, '%d %m %Y');
Given below is PHP code to generate tomorrow's date using mktime() and change its format to dd/mm/yyyy format and then print it using echo.
$tomorrow = mktime(0, 0, 0, date("m"), date("d") + 1, date("Y"));
echo date("d", $tomorrow) . "/" . date("m", $tomorrow). "/" . date("Y", $tomorrow);
Use this function to convert from any format to any format
function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
$date_aux = date_create_from_format($from_format, $date);
return date_format($date_aux,$to_format);
}
In PHP any date can be converted into the required date format using different scenarios for example to change any date format into
Day, Date Month Year
$newdate = date("D, d M Y", strtotime($date));
It will show date in the following very well format
Mon, 16 Nov 2020
date('m/d/Y h:i:s a',strtotime($val['EventDateTime']));
function dateFormat($date)
{
$m = preg_replace('/[^0-9]/', '', $date);
if (preg_match_all('/\d{2}+/', $m, $r)) {
$r = reset($r);
if (count($r) == 4) {
if ($r[2] <= 12 && $r[3] <= 31) return "$r[0]$r[1]-$r[2]-$r[3]"; // Y-m-d
if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$r[2]$r[3]-$r[1]-$r[0]"; // d-m-Y
if ($r[0] <= 12 && $r[1] <= 31) return "$r[2]$r[3]-$r[0]-$r[1]"; // m-d-Y
if ($r[2] <= 31 && $r[3] <= 12) return "$r[0]$r[1]-$r[3]-$r[2]"; //Y-m-d
}
$y = $r[2] >= 0 && $r[2] <= date('y') ? date('y') . $r[2] : (date('y') - 1) . $r[2];
if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$y-$r[1]-$r[0]"; // d-m-y
}
}
var_dump(dateFormat('31/01/00')); // return 2000-01-31
var_dump(dateFormat('31/01/2000')); // return 2000-01-31
var_dump(dateFormat('01-31-2000')); // return 2000-01-31
var_dump(dateFormat('2000-31-01')); // return 2000-01-31
var_dump(dateFormat('20003101')); // return 2000-01-31
For this specific conversion we can also use a format string.
$new = vsprintf('%3$s-%2$s-%1$s', explode('-', $old));
Obviously this won't work for many other date format conversions, but since we're just rearranging substrings in this case, this is another possible way to do it.
Simple way Use strtotime() and date():
$original_dateTime = "2019-05-11 17:02:07"; #This may be database datetime
$newDate = date("d-m-Y", strtotime($original_dateTime));
With time
$newDate = date("d-m-Y h:i:s a", strtotime($original_dateTime));
You can change the format using the date() and the strtotime().
$date = '9/18/2019';
echo date('d-m-y',strtotime($date));
Result:
18-09-19
We can change the format by changing the ( d-m-y ).
Use date_create and date_format
Try this.
function formatDate($input, $output){
$inputdate = date_create($input);
$output = date_format($inputdate, $output);
return $output;
}

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

Add a year to a date in string format using 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.

Why does strtotime gives different values

See the below code
$compDate = date('d/m/y',strtotime('-2 weeks'));
echo strtotime($compDate)."-->".strtotime('-2 weeks');
The echo outputs 1398882600-->1388938336.
Why does the time stamp differ?
This is from the PHP manual:
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 change d/m/y to either d-m-y or m/d/y and strtotime will work perfectly.
Update: Yes, kingkero is right. You have to change d/m/y to either d-m-y H:i:s or m/d/y H:i:s. The point is that you can’t ignore the hour, minute and second.
The first problem is the wrong format - as stated by Sharanya Dutta. The second one is you are losing precision when formatting to m/d/y instead of m/d/y, H:i:s eg.
$compDate = date('m/d/y',strtotime('-2 weeks'));
print date("d.m.Y # H:i:s", strtotime($compDate)); //05.01.2014 # 00:00:00
print date("d.m.Y # H:i:s", strtotime('-2 weeks')); //05.01.2014 # 17:23:42
When you add hours, minutes and seconds to $compDate, it will work as expected
$compDate = date('m/d/y, H:i:s',strtotime('-2 weeks'));
var_dump( strtotime($compDate) === strtotime('-2 weeks')); // TRUE
If you don't need the time but only the date, you can set the time in the strtotime() as well.
$compDate = date('m/d/y',strtotime('-2 weeks'));
var_dump( strtotime($compDate) === strtotime('-2 weeks, 0:0:0')); // TRUE
strtotime assumes x/x/x notation is American and x-x-x notation as European. Since you are passing in d/m/Y as the formatting for $compDate and then passing that date string through strtotime() as second time, it is interpreting the date string as m/d/Y the second time. You can confirm by changing your code like this:
$compDate = strtotime('-2 weeks');
echo $compDate . "-->" . strtotime('-2 weeks');
or this way:
$compDate = date('d-m-y',strtotime('-2 weeks'));
echo strtotime($compDate) . "-->" . strtotime('-2 weeks');
or this way:
$compDate = date('m/d/y',strtotime('-2 weeks'));
echo strtotime($compDate) . "-->" . strtotime('-2 weeks');
A better solution would be to use the DateTime class, which allows you to define the date format of a given string using createFromFormat so that the parser knows which number is which:
$compDate = date('d/m/y',strtotime('-2 weeks'));
$compDateObject = DateTime::createFromFormat('d/m/y', $compDate);
echo $compDateObject->format('U') . "-->" . strtotime('-2 weeks');
That last example is a bit convoluted because generally with a relative string like -2 weeks you wouldn't also need to worry about the formatting, but I'm guessing the issue you're really having is that the date format used throughout your code is in d/m/y, so the above gives an idea of how to swap between that format and and epoch timestamp. If you want to use DateTime to get a relative date (like -2 weeks), you could revamp the above as:
$compDate = new DateTime('-2 weeks');
echo $compDate->format('U') . "-->" . strtotime('-2 weeks');
echo $compDate->format('d/m/Y');
If you want the timestamp to be for the date but don't want to use time, you can add today to the relative format, like so:
$compDate = new DateTime('2 weeks ago today');
echo $compDate->format('U') . "-->" . strtotime('-2 weeks 00:00');
echo $compDate->format('d/m/Y');

How can I get next week dates?

Problem
I'm using the below code to get the next week's date and second week's date. It works fine for first few records but later it starts giving year 1970.
If the start date is 12/01/2013 it shows me coorect result that is:
Next week: 19/01/2013
Second week: 26/01/2013
but in another record where the date is 16/05/2013 it shows the below
Next week: 08/01/1970
Second week: 15/01/1970
Please guide me where I might be going wrong ?
Code
//Date of when game started
$starts_on = '12/01/2013';
//Next week's date from start date
$next_week = strtotime(date("d/m/Y", strtotime($starts_on)) . "+1 week");
$next_week = date('d/m/Y', $next_week);
//Second week's date from start date
$second_week = strtotime(date("d/m/Y", strtotime($starts_on)) . "+2 week");
$second_week = date('d/m/Y', $second_week);
echo $starts_on.", ".$next_week.", ".$second_week;
You are using the wrong format date. Check the note in the strtotime documentation:
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.
Check the documentation further:
Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.
I recommend you use the DateTime Object, is better to manipulate dates (to add and substract dates from another is very easy with the object DateInterval)
<?php
$date = new DateTime("2013-01-12");
//add one week to date
echo $date->add(new DateInterval('P1W'))->format('Y-m-d');
//add one week to date
echo $date->add(new DateInterval('P1W'))->format('Y-m-d');
?>
Result:
2013-01-19
2013-01-26
References:
http://php.net/manual/es/class.datetime.php
http://php.net/manual/es/class.dateinterval.php
Please try this
$dt = new DateTime();
// create DateTime object with current time
$dt->setISODate($dt->format('o'), $dt->format('W')+1);
// set object to Monday on next week
$periods = new DatePeriod($dt, new DateInterval('P1D'), 6);
// get all 1day periods from Monday to +6 days
$days = iterator_to_array($periods);
// convert DatePeriod object to array
echo "<pre>";
print_r($days);

Categories