Convert mm/dd/yy to mm/dd/yyyy in PHP - 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

Related

How to format different types of dates into one?

I have a $birthday that i taken from the database and it shows sometimes 1.12 (DAY.MONTH - without zeros in numbers and without a year) and sometimes as 1.12.1999 (DAY.MONTH.YEAR - without zeros in numbers and with a year)
i need to get a final result for a $birthday as 1.12 (DAY.MONTH - without zeros) and compare it to the current date (CURRENT_DAY.CURRENT_MONTH - without zeros) $today = date("j.n");
if ($birthday == $today ) { echo 'Today is your birthday"; }else{ echo 'Today is not your birthday"; }
How can i do it, how can i format it correctly , because i have different $birthday outputs each time?
You can do it like this.
<?php
$pieces = explode(".", $birthday);
$day = ltrim($pieces[0], '0');
$month = ltrim($pieces[1], '0');
$birthday = $day . "." . $month;
?>
That should give you same format birthday each time without the year and without the leading zeros. Even if input is with or without zeros and with or without a year.
You need to figure out some patterns in the date strings. From the two data points that you've mentioned, I can see one common pattern in the 1.12 and 1.12.1999 date strings which is they both start with day.month. So, if this pattern is held true for all your cases, what simply can be done is to take the first two components of the date string,
$today = date("j.n");
$dateStr = '1.12.1999'; // or 1.12
preg_match('/\d+\.\d+/', $dateStr, $matches);
$isBirthdayToday = isset($matches[0]) && $matches[0] === $today;
I hope this helps.

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{ ... }

Convert MMDDYYYY to date for PHP [duplicate]

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

PHP replace a day number with a variable

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.

Reformat Custom Date in PHP

So I know how to format a date in PHP, but not from a custom format. I have a date that is a string "YYMMDD" and I want to make it "MMDDYYYY'. strtotime doesn't seem like it would do a good job of this when the MM and DD are both low digits.
Use str_split:
$date1 = "YYMMDD";
list($yy, $mm, $dd) = str_split($date1, 2);
// MMDDYYYY format, assuming they are all > 2000
$date2 = $mm . $dd . "20" . $yy;
If you're running PHP >= 5.3, have a look at DateTime::createFromFormat. Otherwise, if you don't want to use pure string manipulation techniques, use the more primitive strptime together with mktime to parse the time into a UNIX timestamp, which you can then format using date.
Maybe I am under-thinking this, but couldn't you just:
$oldDate='040220'; // February 20th, 2004
$year = substr($oldDate, 0,2);
$year += $year &lt 50 ? 2000 : 1900;
$date = preg_replace('/\d{2}(\d{2})(\d{2})/', '$1/$3/'.$year, $oldDate);
And you'd have the string you were looking for, or something close enough to it that you could modify from what I wrote here.
Have many dates prior to 1910? If not, you could check your YY for <=10, and if true, prepend "20" else prepend "19"... Kinda similar approach to MM and DD check for <10 and prepend a "0" if true... (This is all after exploding, or substring... Assign each part to its own variable, i.e. $M=$MM; $D=$DD; $Y=$YYYY; then concatenate/arrange in whatever order you want... Just another potential way to skin the proverbial cat...
Ended up doing:
$expiration_date_year = substr($matches['expiration_date'],0,2);
$expiration_date_month = substr($matches['expiration_date'],2,2);
$expiration_date_day = substr($matches['expiration_date'],4,2);
$expiration_date = date('m/d/Y', mktime(0,0,0,$expiration_date_month, $expiration_date_day, $expiration_date_year));

Categories