I need to format a date in my array - but the date in the array isn't saved as a datetime in a database or something like this.. I've got the dates from my server with cut them out.
So I need to work with preg_replace or with str_replace
What I've tried so far using str_replace:
$reverse_date = str_replace( '[', '' ,$reverse_date);
$reverse_date = str_replace( ']', '' ,$reverse_date);
$reverse_date = str_replace( '/', '.' ,$reverse_date);
but I don't want to use three lines for this.
If I print_r this, I will get : 12.Oct.2015:01:10:43 +0200
before it was looking like this : [12/Oct/2015:00:37:29 +0200]
so this is okay ! But I still don't want to use three lines for this, but I don't understand the preg_replace syntax
I want the following output :
12.Oct.2015(space)01:10:43 +0200
As you have said you were getting a date from an array within the following format
[12/Oct/2015:00:37:29 +0200]
So instead of using str_replace or preg_replace you can simply use DateTime::createFromFormat function of PHP like as
$date = DateTime::createFromFormat("[d/M/Y:H:i:s P]","[12/Oct/2015:00:37:29 +0200]");
echo $date->format('d.M.Y H:i:s P');//12.Oct.2015 00:37:29 +02:00
Demo
Use date_parse to disassemble the date and combine the parts to form your needed result:
[40] boris> $date_array = date_parse(" [12/Oct/2015:00:37:29 +0200] ");
// array(
// 'year' => 2015,
// 'month' => 10,
// 'day' => 12,
// 'hour' => 0,
// 'minute' => 37,
// 'second' => 29,
// 'fraction' => 0,
// 'warning_count' => 0,
// 'warnings' => array(
//
// ),
// 'error_count' => 2,
// 'errors' => array(
// 0 => 'Unexpected character',
// 27 => 'Unexpected character'
// ),
// 'is_localtime' => true,
// 'zone_type' => 1,
// 'zone' => -120,
// 'is_dst' => false
// )
You don't have the month as abbreviated string, but that is trivial to add via an associative array (array(1 => 'Jan', ..., 12 => 'Dec')), and you are on the safe side concerning the date-parsing stuff and future changes in your needs.
Ok I found out how to do it with preg_replace in one line, however I like the Uchiha answer with the date format more - even that he is not using the regex, this is probably the best way to go.
echo preg_replace(['~(?<=\d{4}:\d{2}):~', '~[\[]~', '~[\]]~', '~[\/]~g'],[' ', '', '', '.'],'[12/Oct/2015:00:37:29 +0200]');
12.Oct.2015:00 37:29 +0200
Related
I know how to check for a value in an array, but how do I check for a value in an Array Iterator?
$array = new ArrayIterator(array(
'1QmRjtsw2UQ' => array('pubdate' => '26 Jun 15', 'alt' => '8 Year Old Beautifully Covers Thinking Out Loud', 'anchor text' => '8-yo \'Thinking Out Loud\''),
'eKqLaYrcf3A' => array('pubdate' => '25 Jun 15', 'alt' => 'Plane Lands On Truck', 'anchor text' => 'Plane Lands On Truck'),
));
I'm trying to check for the values such as 1QmRjtsw2UQ.
This does not work:
if(in_array('1QmRjtsw2UQ', $array));
why don't you use array_key_exists ?
if(array_key_exists('1QmRjtsw2UQ', $array))
{
// do something
}
Try this,
$array->offsetExists('1QmRjtsw2UQ');
I posted a question last night that turned out to not be the problem. Digging around, I have discovered that the below code is giving me a headche. I had this working, but now for some reason I get no output. When I var_dump the function that gives me the $finishmins value, it outputs everything correctly until the point where it has to search the array (as below). After this it shows NULL. I was originally using strpos to find out if it started with a zero, then stripped said zero to match to the array, but when it stopped working, I tried the below approach to reduce code.
The point of the code is to convert minutes in time to minutes in decimal notation. I.e. 1 minute = 02, thus 12:01 = 12.02.
$finishmins = '01';
$finishmins = $minarray[$finishmins];
$minarray = array(
00 => '00',
01 => '02',
02 => '03',
03 => '05',
04 => '07',
05 => '08',
06 => '10',
07 => '12',
08 => '13',
09 => '15',
10 => '17',
'18',
// Array continues to 59 => '98'
);
echo $finishmins;
I have pasted the complete code here: http://codepad.org/EUW3n7AB and still can't seem to find the problem.
There are two issues here:
Array indices behave differently between strings and numbers,
Variable scope of $minarray.
$arr[01] and $arr['01'] are not the same thing, so you should be more explicit; in your case you can just leave the array numerically indexed, i.e.:
$minarray = array('00', '02', '03', '05', ...);
Then, you use an (int) cast on the given minutes:
$finishmins = $minarray[(int)$finishmins];
You can solve the second issue by passing the array as a function argument:
function finishtime($minarray, $finish)
Then calling it like so:
echo finishtime($minarray, '12:01');
You have to use the keyword global in your function when referring to the $minarray variable:
function finishtime($finish) {
global $minarray;
$finishx = explode(':', $finish);
$finishhours = $finishx[0];
$finishmins = $finishx[1];
$finishmins;
var_dump($finishmins);
$finishmins = $minarray[$finishmins];
var_dump($finishmins);
$finishtime = $finishhours . '.' . $finishmins;
return $finishtime;
}
[EDIT] : I guess people had problem to understand exactly what I mean, so I completely rewrote my explanations.
I work on a project where users can define a date format used in the whole site. It uses PHP date format standard. For example : "year-month-day" is set by "Y-m-d".
PHP standard uses single-character symbols like Y, m, d, F, j to describe the date format. As seen in the documentation : http://www.php.net/manual/en/function.date.php
Sometimes users can select a date thanks to a jQueryUI Datepicker. This component describes its date format with code-words like yy, y, mm, dd, D, ...
http://api.jqueryui.com/datepicker/#utility-formatDate
I would like to display the dates in the same format for both PHP and the Datepicker.
I mean that PHP should output the date as in the format set by user, AND the Datepicker should show the selected date in the same format.
Given that:
The date format is necessarily described "PHP style"
I can't know a priori which format was set by users
/!\ This not a problem of how to read/parse/display a date from a known format.
Unfortunately, Javascript date format description is not the same as in PHP.
For instance, these 2 date formats are equivalent but described differently in PHP and Javascript:
PHP : Y-m-d (set by users)
Javascript : yy-mm-dd
As you can see, I cannot just configure the datepicker with the PHP date format, because it will be misunderstood, or not recognized at all.
Someone (in answers below) adviced to create my own "date format standard converter", matching each PHP symbol with its equivalent in JS date format description. Just like:
Y => yy
m => mm
d => dd
y => y
z => o
...
And then replace each PHP symbol with the JS one. And so "d/m/Y" will be translated into "dd/mm/yy", magically.
But maybe somebody knows another proper way to make jQueryUI Datepicker understand PHP date format standard?
EDIT: I wrote a tutorial that explains both the problem and the solution. For further reading : http://tristan-jahier.fr/blog/2013/08/convertir-un-format-de-date-php-en-format-de-date-jqueryui-datepicker
I chose the brutal method : converting symbol-by-symbol the date format.
I made a 'not-so-dummy' code snippet.
/*
* Matches each symbol of PHP date format standard
* with jQuery equivalent codeword
* #author Tristan Jahier
*/
function dateformat_PHP_to_jQueryUI($php_format)
{
$SYMBOLS_MATCHING = array(
// Day
'd' => 'dd',
'D' => 'D',
'j' => 'd',
'l' => 'DD',
'N' => '',
'S' => '',
'w' => '',
'z' => 'o',
// Week
'W' => '',
// Month
'F' => 'MM',
'm' => 'mm',
'M' => 'M',
'n' => 'm',
't' => '',
// Year
'L' => '',
'o' => '',
'Y' => 'yy',
'y' => 'y',
// Time
'a' => '',
'A' => '',
'B' => '',
'g' => '',
'G' => '',
'h' => '',
'H' => '',
'i' => '',
's' => '',
'u' => ''
);
$jqueryui_format = "";
$escaping = false;
for($i = 0; $i < strlen($php_format); $i++)
{
$char = $php_format[$i];
if($char === '\\') // PHP date format escaping character
{
$i++;
if($escaping) $jqueryui_format .= $php_format[$i];
else $jqueryui_format .= '\'' . $php_format[$i];
$escaping = true;
}
else
{
if($escaping) { $jqueryui_format .= "'"; $escaping = false; }
if(isset($SYMBOLS_MATCHING[$char]))
$jqueryui_format .= $SYMBOLS_MATCHING[$char];
else
$jqueryui_format .= $char;
}
}
return $jqueryui_format;
}
This function handles all the common codewords between PHP and Datepicker date format standards.
Plus, I added support for character escaping :
d m \o\f Y becomes dd mm 'of' yy
You may still have problems with symbols like 'W', 'L' that have no equivalent handled by Datepicker.
You cannot use the same format with datepicker that you're using with PHP.
Since PHP's date format only uses single letter codes, you're better off just taking the PHP date format and replacing each code to the corresponding value in the jQuery datepicker format, e.g.:
$PHPFormatOptions = array('y', 'Y', 'm', 'd');
$JSFormatOptions = array('yy', 'yyyy', 'mm', 'dd'); // and so on
$JSFormat = str_replace($PHPFormatOptions, $JSFormatOptions, $PHPFormat);
Not sure I'm quite with you, but this really shouldn't be an issue. You could either parse the front-end input: using DateTime::createFromFormat cf. php documentation for this, or use JSON.
Since JSON has an accepted standard way of formatting date strings, you can pass a JSON-stringified version of the input date to PHP, and json_decode it server-side. Both of these solutions are open to you, though I believe the first one to be easier to implement in your case.
If you want to be able to choose the format on both sides, the DateTime object is definitely what you need:
$date = new DateTime();
echo $date->format('Y-m-d').' <==> '.$date->format('y-M-j');
$postDate = $date->createFromFormat('y-m-d',$_POST['submitDate']);
echo $postDate->format('Y-m-d');
The format is explained on the page I've linked to.
Here is the solution:
function datepicker_format($format) {
static $assoc = array(
'Y' => 'yyyy',
'y' => 'yy',
'F' => 'MM',
'm' => 'mm',
'l' => 'DD',
'd' => 'dd',
'D' => 'D',
'j' => 'd',
'M' => 'M',
'n' => 'm',
'z' => 'o',
'N' => '',
'S' => '',
'w' => '',
'W' => '',
't' => '',
'L' => '',
'o' => '',
'a' => '',
'A' => '',
'B' => '',
'g' => '',
'G' => '',
'h' => '',
'H' => '',
'i' => '',
's' => '',
'u' => ''
);
$keys = array_keys($assoc);
$indeces = array_map(function($index) {
return '{{' . $index . '}}';
}, array_keys($keys));
$format = str_replace($keys, $indeces, $format);
return str_replace($indeces, $assoc, $format);
}
The magic double str_replace call caused by duplicating in needles and its replacement values, so that's why the string
m/d/Y
becomes
{{3}}/{{5}}/{{1}}
and after that this nests replacing with actual replacement values:
mm/dd/yy
Ok so the best solution for you would be to store everything in your website using time();
As far as I know datepicker can be set to work with dates for PHP timestamp
dateFormat : 'yy-mm-dd',
Edit :
Why would you store a date like : Y-m-d ?
It should be stored as timestamp or int
I am trying to sort an array in PHP by date and time which is in ISO 8601 format. I am still trying to grasp PHP and have tried many of the solutions on stack overflow and I am just not able to nail down the right function. Hopefully this is an easy answer and it will be helpful to others.
FYI, this array was generated by the Citrix API for GoToMeeting. I would like to sort the array based on startTime in the soonest time first in the list.
Here is what the array looks like using var_export with two results presented:
array (
0 => stdClass::__set_state(
array(
'createTime' => '2012-07-03T19:36:58.+0000',
'status' => 'INACTIVE',
'subject' => 'Client 1',
'startTime' => '2012-07-10T14:00:00.+0000',
'conferenceCallInfo' => 'United States: xxxxx Access Code: xxxxx',
'passwordRequired' => 'false',
'meetingType' => 'Scheduled',
'maxParticipants' => 26,
'endTime' => '2012-07-10T15:00:00.+0000',
'uniqueMeetingId' => 12345678,
'meetingid' => 123456789,
)
),
1 => stdClass::__set_state(
array(
'createTime' => '2012-07-02T21:57:48.+0000',
'status' => 'INACTIVE',
'subject' => 'Client 2',
'startTime' => '2012-07-06T19:00:00.+0000',
'conferenceCallInfo' => 'United States: xxxxx Access Code: xxxxx',
'passwordRequired' => 'false',
'meetingType' => 'Scheduled',
'maxParticipants' => 26,
'endTime' => '2012-07-06T20:00:00.+0000',
'uniqueMeetingId' => 12345678,
'meetingid' => 123456789,
)
),
)
My goal is to then output the array into html div's using a foreach loop, this code is complete and works well but my sort is off :-)
Thank you in advance for any help!
Steve
You can implement any sorting technique you can think of if you wrap it in a callback and use usort() docs here
inside your callback, you can use strtotime or similar, and do simple int comparisons.
$myDateSort = function($obj1, $obj2) {
$date1 = strtotime($obj1->startTime);
$date2 = strtotime($obj2->startTime);
return $date1 - $date2; // if date1 is earlier, this will be negative
}
usort($myArray, $myDateSort);
How can I parse a CSV like this one in PHP (there's a double quote near value 8)?
"03720108";"value 8"";"";"219";"03720108";"value";"value";"value";"";"";"";"";"";"";"value";"";"";"value";"value";
I tried with fgetscv($pointer, 4096, ';', '"');
Your data seems to be malformed starting at the prior line. You have an opening quote with no closing quote.
Yes. Notice the extra quote.
"value 8"";
You might still be able to parse this string, though:
$str = '"03720108";"value 8"";"";"219";"03720108";"value";"value";"value";"";"";"";"";"";"";"value";"";"";"value";"value";';
$parsed = array_map(
function( $str ) { return substr($str, 1, -1); },
explode(';', $str)
);
var_export($parsed);
/*
array (
0 => '03720108',
1 => 'value 8"',
2 => '',
3 => '219',
4 => '03720108',
5 => 'value',
6 => 'value',
7 => 'value',
8 => '',
9 => '',
10 => '',
11 => '',
12 => '',
13 => '',
14 => 'value',
15 => '',
16 => '',
17 => 'value',
18 => 'value',
19 => false,
)
*/
Things get a bit more complicated, though, if there are elements that contain a ; character (normally would be escaped by enclosing the value in quotes... d'oh!), and the above code assumes that you only need to parse a single line (though if you are using fgets() to read the input stream, you should be OK).