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{ ... }
Related
I have
date("M.", $datetime)
I want to get this output:
Jan.
Feb.
Mar.
Apr.
May (no dot necessary)
Jun.
Jul.
…
I dont like the idea of an if-statement to check the length/number of month every time a date is generated.
Is there a approach that is more simple? Like changing the month-name in general? Or hooking into the date function itself to implement an if-statement that runs every time the date function runs.
Thanks
If you don't want the dot to appear after May month, you will need a check of some sort - which normally is an if. You could do something like this, check if the month returned by date() isn't May, and add a dot after if it isn't.
$date = date("M", $datetime);
if (date("M") != "May")
$date .= ".";
Otherwise you'd need to implement a function of your own, but in the end - you will have to end up with this again, there's really no way around it - and this is by far the simplest and cleanest way.
You could wrap this into a function. You can't alter the date() function directly, but you can create one of your own.
function my_date($format, int $timestamp = null) {
if ($timestamp === null)
$timestamp = time();
$date = date($format, $timestamp);
if ($format == "M" && date("M", $timestamp) != "May")
$date .= ".";
return $date;
}
Then use it as
echo my_date("M", $datetime);
This seems to be a bit of a hammer to crack a nut, or to avoid an IF statement in this case, but you can create an array with your month names in it and use that to output different month names if you like
$m_arr = [0,'Jan.','Feb.','Mar.','Apr.','May','Jun.',
'Jul.', 'Aug.', 'Sep.','Oct.','Nov.','Dec.'];
$m = (int)date('n', $datetime);
echo $m_arr[$m];
This question already has answers here:
Parse and reformat a datetime string
(6 answers)
Closed 11 months ago.
I have a string with a date which is in this format MMDDYYYY (ie. 01132012, 01142012 etc.)
I need to do something on a page, if that string is 14 days or less from the current date.
ie. Today is 01132012, so any strings with 12312011 or a less date are going to be showing something on a page.
Can anyone help with this? I've tried
echo date("d/m/Y", strtotime('01142012'));
But to no avail.
You can use the DateTime class of PHP
<?
// current date
$now = new DateTime();
//your date
$date = DateTime::createFromFormat('mdY', '01142012');
// calculate difference
$diff = $now->diff($date);
...
// output the date in format you want
echo $date->format('d/m/Y');
?>
EDIT: I just realized, that your format isn't one supported by php. So you have to use alternate objectbuild.
I prefer using strptime.
<?
$dt = strptime('01142012', '%m%d%Y');
echo sprintf("%02d/%02d/%04d", $dt['tm_mday'], $dt['tm_mon']+1, $dt['tm_year']+1900);
If you use PHP 5.3 or above, you can also use date_parse_from_format()
How about some substr + mktime?
$string = '01142012';
$time = mktime(0, 0, 0,
substr($string, 0, 2),
substr($string, 2, 2),
substr($string, 4, 4)
);
echo date('d/m/Y', $time);
try date('m-d-y', strtotime('01142012'));
could also try something like;
$var = strtotime('01142012');
$var2 = date ('F j, Y', $var);
Your string input of '01142012' cannot be parsed by strtotime() as it is not a valid as it is returning -1 as an answer. To convert this into a valid date you will need to add either slashes or dashes to separate the numbers.
The easiest way would be to store the dates with the dashes or slashes, such as '01-14-2012' or '01/14/2012' in the database from now on or you are going to have to create your own function to convert the numbers into a valid form for strtotime().
To do this you could do something like this:
function makeValidDate($date) {
$valid_date = array();
$array = str_split($date); //split characters up
foreach($array as $key => $character){
if($key==2 || $key==4){
$character = '-'.$character; //add relevant formatting to date
$valid_date[] = $character; //add this to the formatted array
}
else{
$valid_date[] = $character; // if not dashes or slashes needed add to valid array
}
}
return implode($valid_date); // return the formmatted date for use with strtotime
}
You can then do this to get a valid date:
$valid_date = makeValidDate('01142012');
echo date("d/m/Y", strtotime($valid_date));
I haven't tested this but you should get a good idea of what to do.
EDIT: Capi's idea is a lot cleaner!!
try "preg_match(pattern,string on wich the pattern will be aplied)";
http://www.php.net/manual/en/function.preg-match.php
you can also define an offset. so first take te first 2 digits. than take the other 2 digits and after that get the other four digits. after that place them in one string. after that use maketime,strtotime,date. this kind of stupid solution but i only thought of that. hope this will help
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.
I want to get the $registratiedag and count a couple of days extra, but I always get stuck on the fact that it needs to be a UNIX timestamp? I did some google-ing, but I really don't get it.
I hope someone can help me figure this out. This is what I got so far.
$registratiedag = $oUser['UserRegisterDate'];
$today = strtotime('$registratiedag + 6 days');
echo $today;
echo $registratiedag;
echo date('Y-m-d', $today);
There's obviously something wrong with the strtotime('$registratiedag + 6 days'); part, because I always get 1970-01-01
You probably want this:
// Store as a timestamp
$registratiedag = strtotime($oUser['UserRegisterDate']);
$new_date = strtotime('+6 days', $registratiedag);
// You'll need to format for printing $new_date
echo date('Y-m-d', $new_date);
// I think you want to compare $new_date against
// today's date. I'd recommend a string comparison here,
// As time() includes the time as well
// time() is implied as the second argument to date,
// But we'll put it anyways just to be clearer
if( date('Y-m-d', $new_date) == date('Y-m-d', time()) ) {
// The dates are equal, do something here
}
else if($new_date < time()) {
// if the new date is earlier than today
}
// etc.
First it converts $registratiedag to a timestamp, then it adds 6 days
EDIT: You probably should change $today to something less misleading like $modified_date or something
try:
$today = strtorime($registratiedag);
$today += 86400 * 6; // seconds in 1 day * 6 days
at least one of your problems is that PHP does not expand variables in single quotes.
$today = strtotime("$registratiedag + 6 days");
//use double quotes and not single quotes when embedding a php variable in a string
If you want to include the value of variable $registratiedag right into the text passed as parameter of strtotime, you have to enclose that parameter with ", not with '.
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