PHP split a string after certain character, but the string length varies - php

I use a radio button that gives me two variables concatenated and I need to separate them later. It gives me a time and a date in a format 11:30pm3, where 3 is the date and 11:30pm is the time. I can split it fine with my function but if the time is one digit, like 7:30pm for example, it throws things off. I can use military time but that's not what I want.Is there a way to change this so it splits the string right after character "m" so it will work for am/pm, regardless of the length of the time being 7:00am or 07:00am. Thanks in advance.
$string = $Radio; //This is the value I get
$MeetTime = substr("$string", 0, 7); //Gives me 11:30am
$MeetDay = substr("$string", 7, 2); //Gives me 2

find out where the m is and do your logic on that
if m is at 6 then its a full length one
$loc = stripos($string,"m");
if its at 5 then it's short so adjust your split

if(preg_match('~^([\\d]{1,2}:[\\d]{1,2}[ap]m)([\\d]+)$~i', trim($string), $Matches)){
var_dump($Matches); // See what this prints
}
Hope it helps.

try this:
$date = '11:30am3';
$date = explode('pm', $date);
if(count($date) <= 2){
$date = explode('am', $date[0]);
}
print_r($date);
where $date[1] is the time and $day[0] the date.
But you should use somet other format, I'd recommend timestamps.

Related

Add a space in a php string at an exact space

I have lots of date and time data which have been put together like so 05/12/2113:30
What I want to do is separate into two strings like so $date = '05/12/21' and $time = 13:30 so that I can prepare them for database entry in a correct format.
They are always the same first 8 digits (including 2 '/') are the date and the last 5 digits (including ':') are the time.
How can i go about separating them correctly using php?
Thanks so much for your help and I am sure its easy I just seem to be having a brain fart moment.
$value = "05/12/2113:30";
var_dump(substr($value, 0, 8)); //05/12/21
var_dump(substr($value, 8, 5)); //13:30
Using substr() you can extract from any place.
$string = '05/12/2113:30';
$date = substr($string, 0, 8); // 05/12/21 <-- from start
$time = substr($string, -5); // 13:30 <-- from end
You can use substr:
first substring will be date (from 0 to 8)
second substring will be time (from 8 to the end of string)
$date = substr($str,0,8);
$time = substr($str,8);
Using the builtin DateTime Object its actually quite easy when you can guarantee the input format.
$in = '05/12/2113:30';
$dt = (new DateTime())->CreateFromFormat('d/m/yG:i', $in);
echo 'database format = ' . $dt->format('Y-m-d H:i:s');
RESULT
datebase format = 2021-12-05 13:30:00

Converting a non standard date string to a mysql datetime string using php

My intention is to convert the following date
20/04/17 13:27:5
to this
20-04-2017 13:27:05
I tried the typical date format functions of php and also Carbon...
things like
$newDate= Carbon::createFromFormat('d/m/y H:m:s', $originalDate);
in this case
var_dump($newDate->toDateTimeString()) would bring 2019-03-20 13:00:55 which is not what I expect.
So I was not lucky....is there a way to do this in a straight forward manner?
I think this should work.
$date = "20/04/17 13:27:5";
$sec = substr($date, strrpos($date, ":") + 1);
$sec = substr("0{$sec}", -2);
$new = substr($date, 0, strrpos($date, ":") + 1) . $sec;
$newDate = Carbon::createFromFormat('d/m/y H:i:s', $new);
I changed the format since you were using m twice for "minutes" and "month". It is correct for the month, but not for the minutes. Instead use i for minutes with leading zeroes.
$sec Is what I used to get the second from the string. This gets the last position of : and will take everything after it. This assumes that you do not change the format of the string.
substr("0{$sec}", -2) Adds a zero to the current second and extracts the last two characters. That means that 50 becomes 050 and then the last two characters are 50 so we end up without the padding, but 5 becomes 05 and the last two characters are the only characters.
$new concatenates the start of the date string and the new second with the zero padding.
$newDate is your original string with the format changed.
There is issue with seconds. There must be 05 not only 5
<?php
$original_date = "20/04/17 13:27:5";
$date_explode = explode(":", $original_date);
$date_explode[2] = str_pad($date_explode[2],2,"0",STR_PAD_LEFT);
$original_date = implode($date_explode,":");
$date = DateTime::createFromFormat('d/m/y H:i:s', $original_date);
echo date_format($date,"d-m-Y H:i:s");
?>
This is a working conversion routine that creates the ISO format you are looking for. But as already mentioned you need to "fix" the strange way the seconds are specified in the original example you provide. You will have to use string functions if that really is the format you receive. Better would be to fix the code that creates such broken formats.
<?php
$input = '20/04/17 13:27:05';
$date = DateTime::createFromFormat('d/m/y H:i:s', $input);
var_dump($date->format('d-m-Y H:i:s'));
The output obviously is:
string(19) "20-04-2017 13:27:05"
Isn't it like this?
$newDate = Carbon::createFromFormat('d/m/y H:i:s', $originalDate);

PHP convert 2 digit year to a 4 digit year

I have data coming from the database in a 2 digit year format 13 I am looking to convert this to 2013 I tried the following code below...
$result = '13';
$year = date("Y", strtotime($result));
But it returned 1969
How can I fix this?
$dt = DateTime::createFromFormat('y', '13');
echo $dt->format('Y'); // output: 2013
69 will result in 2069. 70 will result in 1970. If you're ok with such a rule then leave as is, otherwise, prepend your own century data according to your own rule.
One important piece of information you haven't included is: how do you think a 2-digit year should be converted to a 4-digit year?
For example, I'm guessing you believe 01/01/13 is in 2013. What about 01/01/23? Is that 2023? Or 1923? Or even 1623?
Most implementations will choose a 100-year period and assume the 2-digits refer to a year within that period.
Simplest example: year is in range 2000-2099.
// $shortyear is guaranteed to be in range 00-99
$year = 2000 + $shortyear;
What if we want a different range?
$baseyear = 1963; // range is 1963-2062
// this is, of course, years of Doctor Who!
$shortyear = 81;
$year = 100 + $baseyear + ($shortyear - $baseyear) % 100;
Try it out. This uses the modulo function (the bit with %) to calculate the offset from your base year.
$result = '13';
$year = '20'.$result;
if($year > date('Y')) {
$year = $year - 100;
}
//80 will be changed to 1980
//12 -> 2012
Use the DateTime class, especially DateTime::createFromFormat(), for this:
$result = '13';
// parsing the year as year in YY format
$dt = DateTime::createFromFormat('y', $result);
// echo it in YYYY format
echo $dt->format('Y');
The issue is with strtotime. Try the same thing with strtotime("now").
Simply prepend (add to the front) the string "20" manually:
$result = '13';
$year = "20".$result;
echo $year; //returns 2013
This might be dumbest, but a quick fix would be:
$result = '13';
$result = '1/1/20' . $result;
$year = date("Y", strtotime($result)); // Returns 2013
Or you can use something like this:
date_create_from_format('y', $result);
You can create a date object given a format with date_create_from_format()
http://www.php.net/manual/en/datetime.createfromformat.php
$year = date_create_from_format('y', $result);
echo $year->format('Y')
I'm just a newbie hack and I know this code is quite long. I stumbled across your question when I was looking for a solution to my problem. I'm entering data into an HTML form (too lazy to type the 4 digit year) and then writing to a DB and I (for reasons I won't bore you with) want to store the date in a 4 digit year format. Just the reverse of your issue.
The form returns $date (I know I shouldn't use that word but I did) as 01/01/01. I determine the current year ($yn) and compare it. No matter what year entered is if the date is this century it will become 20XX. But if it's less than 100 (this century) like 89 it will come out 1989. And it will continue to work in the future as the year changes. Always good for 100 years. Hope this helps you.
// break $date into two strings
$datebegin = substr($date, 0,6);
$dateend = substr($date, 6,2);
// get last two digits of current year
$yn=date("y");
// determine century
if ($dateend > $yn && $dateend < 100)
{
$year2=19;
}
elseif ($dateend <= $yn)
{
$year2=20;
}
// bring both strings back into one
$date = $datebegin . $year2 . $dateend;
I had similar issues importing excel (CSV) DOB fields, with antiquated n.american style date format with 2 digit year. I needed to write proper yyyy-mm-dd to the db. while not perfect, this is what I did:
//$col contains the old date stamp with 2 digit year such as 2/10/66 or 5/18/00
$yr = \DateTime::createFromFormat('m/d/y', $col)->format('Y');
if ($yr > date('Y')) $yr = $yr - 100;
$md = \DateTime::createFromFormat('m/d/y', $col)->format('m-d');
$col = $yr . "-" . $md;
//$col now contains a new date stamp, 1966-2-10, or 2000-5-18 resp.
If you are certain the year is always 20 something then the first answer works, otherwise, there is really no way to do what is being asked period. You have no idea if the year is past, current or future century.
Granted, there is not enough information in the question to determine if these dates are always <= now, but even then, you would not know if 01 was 1901 or 2001. Its just not possible.
None of us will live past 2099, so you can effectively use this piece of code for 77 years.
This will print 19-10-2022 instead of 19-10-22.
$date1 = date('d-m-20y h:i:s');

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

Categories