PHP replace a day number with a variable - php

I have this code:
$x = date("Y-m-d", strtotime($post['commissionEligibilityDate'] . "+ " . $post['billingPeriodExpiration'] . " months"))
$post['commissionEligibilityDate'] = 2011-11-08 <br/>
$post['billingPeriodExpiration'] = 2 <br/>
so $x returns 2012-01-08.
I have another variable $singleDate and it's equal to 1. What I am trying to do replace the 08 with 01. How can I do that?

You don't have to use Y-m-d, you can use Y-m-01 or your variable:
$x = date("Y-m-".$singleDate, strtotime($post['commissionEligibilityDate'] . "+ " . $post['billingPeriodExpiration'] . " months"))

You could use the DateTime class:
$d = new DateTime($x);
$year = $d->format('Y');
$month = $d->format('m');
$d->setDate($year, $month, '01');
echo $d->format('Y-m-d');

str_replace('08','01',$post['commissionEligibilityDate']);

$explode = explode("-",$post['commissionEligibilityDate']);
$explode[2] = $singleDate;
$post['commissionEligibilityDate'] = implode("-",$explode);
$post['commissionEligibilityDate'] will now echo 2011-11-1

Almost anything is possible with PHP. My suggestion seeing as your looking to only get one number from a date that you consider checking out http://php.net/manual/en/function.date.php to see the various ways of handling the date() output. As you could easily output a day then add to it $z = date('d', time())+1; for example.
I am not sure what your doing with your dates specifically but to me it sounds like you might have a misconception of what they are, and how to work with them. Basically the short idea of it is, a date defined in a variable is a string. You can make them anyway you want even without the use of date() then store them, as long as they are in the right format when you go to store them ie yyyy-mm-dd you should be fine.

Related

Merge Date and Time into one variable in php

I have got 2 variables like:
$date //2011-01-01
$full_old_date //1999-01-01 12:00:00
Now I want to combine the new date and the time of the $full_old_date together as a new variable like:
$full_new_date //2011-01-01 12:00:00
What should I do to extract only the time from the old one and combine them together as a new date variable?
Hope this helps (assuming you have these values as 'strings' and not date/timestamps):
$date = "2011-01-01";
$full_old_date = "1999-01-01 12:00:00"
$full_new_date = $date . ' ' . trim(substr($full_old_date,-8));
//substr() - This gets the last 8 characters of the $full_old_date variables
//trim() - This function removes any whitespace at the edges of the substring
There are many ways to do this, however this is one way of doing it.
This solution may help you
$date ="2011-01-01";
$full_old_date ="1999-01-01 12:00:00";
function newDate($date,$full)
{
return $date . " " . explode(" ",$full)[1];
}
echo newDate($date,$full_old_date);
You can use preg_replace like this
$date = "2011-01-01";
$full_old_date = "1999-01-01 12:00:00";
echo $new_date = preg_replace('/\d{4}-\d{1,2}-\d{1,2}/', $date, $full_old_date);

Add 1 year to a date

I have a date 01/31/2014, and I need to add a year to it and make it 01/31/2015. I am using
$xdate1 = 01/31/2014;
$xpire = strtotime(date("m/d/Y", strtotime($xdate1)) . " +1 year");
But it is returning 31474800.
Waaaay too complicated. You're doing multiple date<->string conversions, when
php > $x = strtotime('01/31/2014 +1 year');
php > echo date('m/d/Y', $x);
01/31/2015
would do the trick.
Another way is below:
<?php
$date = new DateTime('2014-01-31');
$date->add(new DateInterval('P01Y'));
echo $date->getTimestamp();
?>
There are 2 mistakes here.
You are missing the quote sign " when assigning to $xdate1. It should be
$xdate1 = "01/31/2014";
And the second, to get "01/31/2015", use the date function. strtotime returns a timestamp, not a date format. Therefore, use
$xpire = date("m/d/Y", strtotime(date("m/d/Y", strtotime($xdate1)) . " +1 year"));
May I introduce a simple API extension for DateTime with PHP 5.3+:
$xdate1 = Carbon::createFromFormat('m/d/Y', '01/31/2014');
$xpire = $xdate1->addYear(1);
First make $xdate1 as string value like
$xdate1 = '01/31/2014';
then apply date function at it like bellow
$xpire = date('m/d/Y', strtotime($xdate1.' +1 year')); // 01/31/2015

PHP - Split ugly date string and then do date maths on it?

I'm a PHP beginner and been struggling unsuccessfully with the php documentation. Seems a lot of ways to do what I want.
Basically I need a php page to check an "ugly" date/time variable appended to a URL - it must convert it into a usable format and subtract it from the current date/time. If the result is less than 48hrs then the page should redirect to "Page A" otherwise it should redirect to "Page B"
This is what the URL and variable looks like.
http://mysite.com/special-offer.php?date=20130527212930
The $date variable is the YEAR,MONTH,DAY,HOUR,MINUTE,SECOND. I can't change the format of this variable.
I'm guessing PHP can't use that string as it is. So I need to split it somehow into a date format PHP can use. Then subtract that from the current server date/time.
Then put the result into an if/else depending on whether the result is more or less than 48hrs.
Am I right in theory? Can anyone help me with the "practise"?
Thanks!
Take a look at the DateTime class and specifically the createFromFormat method (php 5.3+):
$date = DateTime::createFromFormat('YmdHis', '20130527212930');
echo $date->format('Y-m-d');
You might need to adjust the format depending on the use of leading zeros.
PHP 5 >= 5.3.0
$uglydate = '20130527212930';
// change ugly date to date object
$date_object = DateTime::createFromFormat('YmdHis', $uglydate);
// add 48h
$date_object->modify('+48 hours');
// current date
$now = new DateTime();
// compare dates
if( $date_object < $now ) {
echo "It was more than 48h ago";
}
You can use a regular expression to read your string and construct a meaningful value.
for example
$uglydate = "20130527212930";
preg_match("/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/", $uglydate, $matches);
$datetime = $matches[1] . "-" . $matches[2] . "-" . $matches[3] . " " . $matches[4] . ":" . $matches[5] . ":" . $matches[6];
//then u can use $datetime in functions like strtotime etc
Whoa! you all have WAY too much time on your hands... Nice answers... oh well, i'll pop-in a complete solution...
<?php
$golive = true;
if (preg_match('|^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})|', $_GET['date'], $matches)) {
list($whole, $year, $month, $day, $hour, $minute, $second) = $matches;
// php: mktime function (using parameters derived
$timestamp = mktime($hour,$minute,$second,$month,$day,$year);
$diff = time()-$timestamp;
$diffInHours = $diff / 3600 ;
// if less, than 48
if ( $diffInHours < 48 ) {
$location = "http://bing.com";
} else {
$location = "http://google.com";
}
//
if ( $golive ) {
header("Location: ".$location);
exit();
} else {
echo "<p>You are would be sending the customer to:<br><strong>$location</strong>";
}
} else {
echo "<p>We're not sure how you got here, but... 'Welcome!'???</p>";
}
That oughta do it.
By the way, on another note, I'd heavily suggest you go back to the sending party of that URL and definitely reconsider how this is being done. As this is VERY easily tweakable (URL date= value), thus not really protecting anything, but merely putting the keys on the front porch next to the 'Guardian Alarms Installed at This House' {sign} :).
Assuming the input is in the correct format (correct number of characters and all of them digits) you'll need 1 substring of length 4 and the rest of lenght 2. For simplicity I'll ignore the first 2 chars (the 20 part from 2013) with substr
$input=substr($input, 2, strlen($input));
Now I can treat all the remaining elements in the string as 2-char pairs:
$mydate=array(); //I'll store everything in here
for($i=0; $i<=strlen($input)-2; $i+=2){
$mydate[$a]=substr($input, $i, $i+2);
$a++;
}
Now I have year, month, day etc. in an array indexed from 0 to 5. For the date difference I'll put the array into mktime:
$timestamp = mktime(mydate[3], mydate[4], mydate[5], mydate[1], mydate[2], mydate[0]);
Finally compare the two timestamps:
if($old_ts - $timestamp > (60*60*48)){
//more than 48 hours
}else{ ... }

Get time from a date/time string

I have a date value stored in a variable. I need to extract the time part of the value in to a separate variable and then add/subtract time from it.
The date variable is set with date('YmdHis'), giving (for example) 20110805124000 for August 5th 2011, 12:40:00
From the value 20110805124000 (which is stored in the variable $fulltime), I need to store the time only in the format 12:40 (so ignoring the year, month, day and seconds and adding the colon between the hour and minute) in a variable called $shorttime. I then need to add a number of hours to that time (so for example +3 hours would change the value in the $shorttime variable to 15:40). The number of hours I need to add is stored in a variable called $addtime, and this value could be a negative number.
Is this easily doable? Could anyone help?
Thanks :)
$time = '2013-01-22 10:45:45';
echo $time = date("H:i:s",strtotime($time));
It will give the time 10:45:45 from datetime.
<?PHP
$addhours = 3;
$date = DateTime::createFromFormat('YmdHis', '20110805124000');
$shorttime = $date->format("H:i");
$newdate = $date->add(DateInterval::createFromDateString($addhours . "hours"));
$newtime = $newdate->format("H:i");
echo $shorttime . "<br />";
echo $newtime . "<br />";
?>
for your reference:
http://www.php.net/manual/en/datetime.createfromformat.php
http://www.php.net/manual/en/dateinterval.createfromdatestring.php
hello the way I usually do it is like this, maybe it's a bit long but it works for me...
$DateIn = new DateTime($In);
$DateOut = new DateTime($Out);
$HourOut = new DateTime($H_Out);
$FechaEntrada = $DateIn->format('d-m-Y');
$FechaSalida = $DateOut->format('d-m-Y');
$HoraSalida = $HourOut->format('H:i a');
the guide I used was the PHP one DateTime::format()

Convert mm/dd/yy to mm/dd/yyyy in PHP

I'm working on a project that requires me to read values from a file and manipulate them slightly before storing them elsewhere. One of the things I need to do is convert some dates from mm/dd/yy format to mm/dd/yyyy format. Unfortunately for me, I am relatively new to PHP and regular expressions (which I assume is one of the better ways to solve this problem), and am therefore somewhat mystified. Any and all help will be appreciated. Thanks!
PHP has a built-in function strtotime() that is meant for just this kind of task... it'll even do the best-guess for the 2-digit year following this rule: the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999. Once you have the date/time in the UNIXy format that PHP prefers, then you can print it out however you want with the date() function.
<?php
$str = '02/28/98';
// in PHP 5.1.0+, strtotime() returns false if it fails
// previous to PHP 5.1.0, you would compare with -1 instead of false
if (($timestamp = strtotime($str)) === false) {
echo "Couldn't figure out the date ($str)!";
} else {
echo "Reformatted date is " . date('m/d/Y', $timestamp);
}
?>
(I presume we're timezone-agnostic here, or that would add complications.)
You can try this, it may or may not work:
$new_date = date( 'm/d/Y', strtotime( $old_date ) );
Where $old_date is in the format you're talking about.
One of the problems here is that YY, assuming it is relatively current, can be either 19YY or 20YY. This means you should pick a number to be the cut off. Let's call this $cutOff If YY is less than $cutOff, we want 20YY if greater than we want 19YY
You could do it with regex, but since your example is simple and regex tends to be slower, you can simply use string manipulation with substr and substr_replace.
Here's how to change a string mm/dd/yy int mm/dd/yyyy:
<?php
// Our date
$str = "01/04/10";
$cutoff = 50;
// See what YY is
// Get the substring of $str starting two from the end (-2)... this is YY
$year = substr($str, -2);
// Check whether year added should be 19 or 20
if ($year < 50)
// PHP converts string to number nicely, so this is our 20YY
$year += 2000;
else
// This is 19YY
$year += 1900;
// Repace YY with YYYY
// This will take $str and replace the part two from the end (-2) undtil
// the end with $year.
$str = substr_replace($str, $year, -2);
// See what we got
echo $str;
?>
You can append the year starting two values (19 or 20) as below:
//for $s_date = "yy-dd-mm"
if (substr($s_date,6,2) >= 50){
$standarddate = "19" . substr($s_date,6,2); //19yy
$standarddate .= "-" . substr($s_date,0,2); //mm
$standarddate .= "-" . substr($s_date,3,2); //dd
} else {
$standarddate = "20" . substr($s_date,6,2); //20yy
$standarddate .= "-" . substr($s_date,0,2); //mm
$standarddate .= "-" . substr($s_date,3,2); //dd
}
// you will get yyyy-mm-dd

Categories