I have a php page listed below with events and I wish to order them by dates. No problem with this, but I want the date format was "15/Lug/1998" and not "15/Lug/1998:00:00:00 -0000". I post the code to fix this problem. Thanks in advance for your reply and help.
<?php
# For demo - some data that we will test with
$stuff = <<<COURSES
02 - - [15/Lug/1998:00:00:00 -0000] "Event01"
05 - - [21/Lug/1998:00:00:00 -0000] "Event02"
07 - - [16/Lug/1998:00:00:00 -0000] "Event03"
COURSES;
# Date in yukky format to Unix timestamp
function gdate($record) {
eregi('\[([0-9]{2})/([A-Z]{3})/([0-9]{4}):([0-9]{2}):([0-9]{2}):([0-9]{2})',
$record, $gotten);
$yikes = 1 + (strpos("GenFebMarAprMagGiuLugAgoSetOttNovDic",
$gotten[2]))/3; # Date "Alpha Triplet" to Month No.
$when = mktime($gotten[4],$gotten[5],$gotten[6],
$yikes,$gotten[1],$gotten[3]);
return $when;
}
function bydate($left,$right) {
$whenone = gdate($left);
$whentwo = gdate($right);
if ($whenone == $whentwo) return 0;
return (($whenone < $whentwo) ? -1 : +1);
}
$records = explode("\n",$stuff);
sort ($records);
$result = implode("<br />",$records);
print "<hr> Normal sort</br>$result";
usort ($records,bydate);
$result = implode("<br />",$records);
print "<hr> User defined sort - by date stamp</br>$result";
?>
Your timestamp is generated through below code
function gdate($record) {
eregi('\[([0-9]{2})/([A-Z]{3})/([0-9]{4}):([0-9]{2}):([0-9]{2}):([0-9]{2})',
$record, $gotten);
$yikes = 1 + (strpos("GenFebMarAprMagGiuLugAgoSetOttNovDic",
$gotten[2]))/3; # Date "Alpha Triplet" to Month No.
$when = mktime($gotten[4],$gotten[5],$gotten[6],
$yikes,$gotten[1],$gotten[3]);
return $when;
}
Modify it like below:
function gdate($record) {
eregi('\[([0-9]{2})/([A-Z]{3})/([0-9]{4}):([0-9]{2}):([0-9]{2}):([0-9]{2})',
$record, $gotten);
$yikes = 1 + (strpos("GenFebMarAprMagGiuLugAgoSetOttNovDic",
$gotten[2]))/3; # Date "Alpha Triplet" to Month No.
$time = mktime($gotten[4],$gotten[5],$gotten[6],
$yikes,$gotten[1],$gotten[3]);
$when = date('d/M/Y', $time); //this is solution one, recommended
$when = substr($time, 0, -15); //this is solution two
return $when;
}
EDIT:
Remain your previous code and modify below part:
$records = explode("\n",$stuff);
TO:
$rec = str_replace(":00:00:00 -0000", "", $stuff);
$records = explode("\n",$rec);
Second EDIT:
Change: (Change two places)
$result = implode("<br />",$records);
To:
$result = implode("<br />",str_replace(":00:00:00 -0000", "", $stuff));
Related
I've a string like below
$num = "20142311.235504";
I want to split the string in below format
$date['year'] = 2014;
$date['Month'] = 23;
$date['day'] = 11;
$date['hour'] = 23;
$date['min'] = 55;
$date['sec'] = 04;
or even in date form like below
2014/23/11 23:55:04
I tried using preg_split('/(d{4})/',$num,$matches); and str_split but am not getting the desired output. Your help is highly appreciated.
If the string is a date, you can do this :
$num = "20142311.235504";
// You create a date with your string according to your current format
$date = date_create_from_format("Ydm.His", $num);
// Now you can play with it
$formattedDate = $date->format("Y/d/m H:i:s"); // `string(19) "2014/23/11 23:55:04"`
$dateTest['year'] = $date->format("Y"); // 2014
$dateTest['Month'] = $date->format("m"); // 11
$dateTest['day'] = $date->format("d"); // 23
$dateTest['hour'] = $date->format("H"); // 23
$dateTest['min'] = $date->format("i"); // 55
$dateTest['sec'] = $date->format("s"); // 04
Demo here : http://sandbox.onlinephpfunctions.com/
With the help of regex you can do this. In pattern create capture group for garbing year, months, days, hours, minutes and seconds. Simple example:
$str = "20142311.235504";
preg_match('~^(?<year>\d{4})(?<day>\d{2})(?<month>\d{2}).(?<hour>\d{2})(?<minute>\d{2})(?<second>\d{2})$~', $str, $match);
echo '<pre>', print_r($match);
But I prepare you to use date_create_from_format() which is more easier and faster than regex. First, convert a known date format separated by -, explode that format to convert an array and finally assign the array to a set of key [by array_combine()]. Example:
$str = "20142311.235504";
$match = array_combine(['year', 'month', 'day', 'hour', 'minute', 'second'], explode('-', (date_create_from_format("Ydm.His", $str))->format('Y-m-d-H-i-s')));
echo '<pre>', print_r($match);
I'm beginner in php, I really need help, I have a question everybody help me please, I'm making a scraping data, from other website,the website have data like 07 Ogos 2015. when I write this in controller
public function UMKDATA()
{
$data = array();
$this->load->library('simple_html_dom');
$this->load->model('Vtender_Data');
// create HTML DOM
$html = file_get_html("http://www.umk.edu.my/index.php/en/component/k2/item/180-tender-dan-sebutharga");
// get title
$strA = $html->find('.itemFullText tbody tr');
$j = 0;
foreach($strA as $strB)
{
if($j >= 1)
{
$strB->innertext;
$strC = str_get_html($strB->innertext);
$masuk['Title'] = str_get_html($strB->find('td',1)->innertext)->find('span',0)->plaintext;
if($this->Vtender_Data->check($masuk['Title']) == 0)
{
$masuk['source'] = $strC->find('td',0)->plaintext;
// $masuk['Opening_Date'] = $strC->find('td',2)->plaintext;
$masuk['Posted_Date'] = date('y-m-d', strtotime($strC->find('td',3)->innertext));
//$masuk['Posted_Date'] = $strC->find('td',3)->plaintext;
$masuk['Document'] = str_get_html($strC->find('td',4)->innertext)->find('a',0)->href;
$masuk['URLNAME'] = 'UMK' ;
$this->Vtender_Data->masuk($masuk);
}
}
$j++;
}
}
Date Posted_Date in my db look like this 1970-01-01, what should I do? I have to change the language or what, so that data in db correct and look like 2015-08-09.
You have to write:
date("Y-m-d H:i:s");
Y means: A full numeric representation of a year, 4 digits
y means: A two digit representation of a year
look at: http://php.net/manual/en/function.date.php
I have an array say:
array("10:10:20", "-20:00:10", "14:15:00", "08:10:00");
I tried using strtime but it is giving me error as it cant convert negative values to timestamp. Is there any another way?
After rereading the question I made a little snippet, the average is a sum of numbers. So i'm guessing this should be correct. To bypass the negative timestamps, you just need to calculate the absolute one, make it negative and add it to the sum.
<?php
$timings = array("10:10:20", "-20:00:10", "14:15:00", "08:10:00");
//$timings = array("-10:10:20", "-10:10:20", "-10:10:20", "-10:10:20");
$totalTime = 0;
foreach($timings as $timing) {
$isNegativeTime = strpos($timing, '-') !== false;
$time = strtotime(str_replace('-', '', $timing));
if ($isNegativeTime) $time *= -1;
$totalTime += $time;
}
$avgTiming = $totalTime / count($timings);
$isNegativeAvgTime = $avgTiming < 0;
$avgTiming = date('h:i:s', abs($avgTiming));
echo ($isNegativeAvgTime ? '-':'').$avgTiming;
<?php
$moredownvotes = array("10:10:20", "-20:00:10", "14:15:00", "08:10:00");
$nb_lol = count($moredownvotes);
for ($i = 0; $i < ($nb_lol - 1); ++$i)
{
$pattern = '/^-(.*)/';
$replacement = '${1}';
$moredownvotes[$i] = preg_replace($pattern, $replacement, $moredownvotes[$i]);
}
print "<pre>";
print_r($moredownvotes);
print "</pre>";
?>
Result :
Array
(
[0] => 10:10:20
[1] => 20:00:10
[2] => 14:15:00
[3] => 08:10:00
)
NOW u can use DateTime functions or w/e u want
$date = DateTime::createFromFormat('H:i:s', $moredownvotes[$i]);
echo date_format($date, 'H:i:s');
**RESULT ** : 10:10:20
PHP.net createFromFormat function
Ideally what should happen is, based on the in-game date that the site is set to (currently its 3014-11-16) the site should calculate a characters current age and return that age. So if we set the Year to ignore year to 10 and a characters Date of Birth to 2, we would get an age of 8.
The current date is set to: 3014-11-16 (yyyy-mm-dd)
The date of birth for timber wolf is: 2998-01-12 (yyyy-mm-dd)
His age should display as 16, instead it displays as -55
If i set his DOB to: 3013-11-16, his age become -71
If i set his DOB to: 3012-11-16, his age come back -70
If i set his DOB to: 3005-11-16, his age comes back as -63 instead of 7
If i set his DOB to: 2998-11-16, his age comes back as -56 instead of 16
If i set his DOB to: 2945-11-16, his age come back as -3
If i set his DOB to: 2944-11-16, his age comes back as -1
If i set his DOB to: 2943-11-16, his age comes back as 0
If i set his DOB to: 2105-11-16, his age come back 837 instead of 909
I've tried to minimize the code by removing a lot of the key array and parts that are not related to the problem. If I set the $age at the very last line to $age=15, I get fifteen, so I know that I am trying to revise the value being returned to the $age variable, but I'm completely lost after many attempts.
I'm looking for a way to get the correct age of the character. Thats my goal, hopefully someone out there can see what i'm doing wrong.
Here is the relevant code:
require_once('../include/Application.php'); // The only class we need to include
$app = new Application(); // Create the initial application object
$app->connect(); // Connect to the mysql server
$sess = new Session(); // Start a new session
$current = new CurrentUser(FALSE);
if ($current->errors) {
$errors = $current->errors;
trigger_error(current($errors), E_USER_ERROR);
}
include ("../functions.php");
$id="";
$record=array();
approveVars(array("id"));
$PHP_SELF = $_SERVER["PHP_SELF"];
$errors = array();
// Get daytimes from db
$daytimes = new DaytimeList();
if ($daytimes->errors) {
$errors = $daytimes->errors;
trigger_error(current($errors), E_USER_ERROR);
}
// Get the current game from the db
require_once('../include/Game.php');
$cu_game = new Game();
$cu_game->selectCurrent();
if ($cu_game->errors) { // Query error
$errors = $cu_game->errors;
trigger_error(current($errors), E_USER_ERROR);
} elseif ($cu_game->id) { // We got the current game
list($gametime, $realtime, $daylength, $inittod) = array(htmlspecialchars($cu_game->gametime, ENT_QUOTES), htmlspecialchars($cu_game->realtime, ENT_QUOTES), $cu_game->daylength/604800, htmlspecialchars($daytimes->data[$cu_game->inittod], ENT_QUOTES));
}
/*
$gametimefile = "$basefile/gamedate/gamedate.txt";
$tempy = file($gametimefile);
$gametime = trim($tempy[0]);
$realtime = trim($tempy[1]);
*/
if ($id) {
// FORMULA FOR GAME TIME
// FROM_DAYS(TO_DAYS('$gametime') + FLOOR((TO_DAYS(NOW()) - TO_DAYS('$realtime')) /14))
if (!is_numeric($id)) {
$characterSQL = "SELECT *, DATE_FORMAT(lastmodified,'%b %e # %h:%i %p') AS modformat, TO_DAYS(NOW()) - TO_DAYS(lastmodified) as modage, IFNULL(FLOOR((TO_DAYS('$gametime') + FLOOR((TO_DAYS(NOW()) - TO_DAYS('$realtime')) / 14) - TO_DAYS(dateofbirth)) / 365.25) ,0) AS age, DATE_FORMAT(dateofbirth, '%b %e, %Y') AS dateofbirth, datecreated AS dateadded FROM cerebra where codename=\"". mysql_real_escape_string($id) . "\"";
} else {
$characterSQL = "SELECT *, DATE_FORMAT(lastmodified,'%b %e # %h:%i %p') AS modformat, TO_DAYS(NOW()) - TO_DAYS(lastmodified) as modage, IFNULL(FLOOR((TO_DAYS('$gametime') + FLOOR((TO_DAYS(NOW()) - TO_DAYS('$realtime')) / 14) - TO_DAYS(dateofbirth)) / 365.25) ,0) AS age, DATE_FORMAT(dateofbirth, '%b %e, %Y') AS dateofbirth, datecreated AS dateadded FROM cerebra where id=\"" . mysql_real_escape_string($id) . "\"";
} // end if'
$result=mysql_query($characterSQL, $db);
if (!mysql_num_rows($result)) { errorpage("There is no Cerebra record with that id number. Please check the link you used to access this page and try again, or check the <a href='/cerebra.php'>Cerebra main page</a> for the record you're looking for."); die; }
$record = mysql_fetch_assoc($result);
$id = $record["id"];
} else {
header("location: /cerebra.php");
die; } // end if ID
// "modelname","song","song_link"
//"Model", "Song", "Song Link",
$fields = array(
"Age"=>"age",
"Apparentage Age"=>"apparentage",
"Base Of Operations"=>"baseofoperations",
"Birthdate"=>"dateofbirth"
);
$patterns = array ("/\"/","/[\n\r\f]+/");
$replace = array (""","</p>\n<p>");
FOREACH ($fields as $label => $field) {
${$field} = preg_replace($patterns, $replace, trim($record[$field]));
${$field . "Name"} = $label;
} // end FOREACH
if ($age > "2000") { $age =""; }
//if i set $age = 15 here, then character age will appear as 15...
I'd like to know if there is a formatting letter for PHP's date() that allows me to print minutes without leading zeros, or whether I have to manually test for and remove leading zeros?
Use:
$minutes = intval(date('i'));
For times with more information than just minutes:
ltrim() - Strip whitespace (or other characters) from the beginning of a string
ltrim(date('i:s'), 0);
returns:
8:24
According to the PHP Documentation, the date() function does not have a placeholder for minutes without leading zeros.
You could, however, get that information by simply multiplying the dates, with a leading zero, by 1, turning it into an integer.
$minutesWithoutZero = 1* date( 'i' );
I tried to find this for seconds as well, gave up the search and just casting the result as a int like this:
echo (int)date("s");
That will get rid of the leading zero's in a fast efficient way.
Doesn't look like it, but you could do something like...
echo date('g:') . ltrim(date('i'), '0');
Alternately, you could cast the second call to date() with (int).
This also works
$timestamp = time(); // Or Your timestamp. Skip passing $timestamp if you want current time
echo (int)date('i',$timestamp);
I use this format if I need a XXmXXs format:
//Trim leading 0's and the 'm' if no minutes
ltrim(ltrim(gmdate("i\ms\s", $seconds), '0'), 'm');
This will output the following:
12m34s
1m23s
12s
i just did this one line solution
$min = intval(date('i',strtotime($date)));
Using ltrim method may remove all the leading zeroes.For ex if '00' min.In this case this will remove all the zeroes and gives you empty result.
My solution:
function seconds2string($seconds) {
if ($seconds == 0) {
return '-';
}
if ($seconds < 60) {
return date('0:s', $seconds);
}
if ($seconds < 3600) {
return ltrim(date('i:s', $seconds), 0);
}
return date('G:i:s', $seconds);
}
This will output:
0 seconds: -
10 seconds: 0:10
90 seconds: 1:30
301 seconds: 5:01
1804 seconds: 30:04
3601 seconds: 1:00:01
Just use this:
(int) date('i');
Or in mySQL just multiply it by 1, like such:
select f1, ..., date_format( fldTime , '%i' ) * 1 as myTime, ..., ...
$current_date = Date("n-j-Y");
echo $current_date;
// Result m-d-yy
9-10-2012
A quickie from me. Tell me what you think:
<?php function _wo_leading_zero($n) {
if(!isset($n[1])) return $n;
if(strpos($n, '.') !== false) {
$np = explode('.', $n); $nd = '.';
}
if(strpos($n, ',') !== false) {
if(isset($np)) return false;
$np = explode(',', $n); $nd = ',';
}
if(isset($np) && count($np) > 2) return false;
$n = isset($np) ? $np[0] : $n;
$nn = ltrim($n, '0');
if($nn == '') $nn = '0';
return $nn.(isset($nd) ? $nd : '').(isset($np[1]) ? $np[1] : '');
}
echo '0 => '._wo_leading_zero('0').'<br/>'; // returns 0
echo '00 => '._wo_leading_zero('00').'<br/>'; // returns 0
echo '05 => '._wo_leading_zero('05').'<br/>'; // returns 5
echo '0009 => '._wo_leading_zero('0009').'<br/>'; //returns 9
echo '01 => '._wo_leading_zero('01').'<br/>'; //returns 1
echo '0000005567 => '._wo_leading_zero('0000005567').'<br/>'; //returns 5567
echo '000.5345453 => '._wo_leading_zero('000.5345453').'<br/>'; //returns 0.5345453
echo '000.5345453.2434 => '._wo_leading_zero('000.5345453.2434').'<br/>'; //returns false
echo '000.534,2434 => '._wo_leading_zero('000.534,2434').'<br/>'; //returns false
echo date('m').' => '._wo_leading_zero(date('m')).'<br/>';
echo date('s').' => '._wo_leading_zero(date('s')).'<br/>'; ?>
use PHP's absolute value function:
abs( '09' ); // result = 9
abs( date( 'i' ) ); // result = minutes without leading zero
My Suggestion is Read this beautiful documentation it have all details of php date functions
Link of Documentation
And as per your question you can use i - Minutes with leading zeros (00 to 59) Which return you minutes with leading zero(0).
And Also introducing [Intval()][2] function returns the integer value of a variable. You can not use the intval() function on an object