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
Related
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);
I inherited a database that stores the times as 900 for 9:00am and 1500 for 3:00pm. How can I convert these numbers to normal time formats in PHP?
Use the PHP mktime() function. So you would do something like this:
$hour = substr($time, 0, -2); // Get everything before last two chars of string
$minute = substr($time, -2); // Gets last two chars of string
$newtime = mktime($hour, $minute);
Then use PHP date() to format it how you want.
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.
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'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