I am new to cakephp and i wish to do the following:
I have a dateTime object and i want to add and subtract 30 minutes to it.
Following is my code in controller :
$time = $this->request->data['Rideoffer']['DepartureTime'];
$date = new DateTime($time['hour'] . ':' . $time['min'] . ' ' . $time['meridian']);
$currentDate = strtotime($date['date']); // this line gives error
$futureDate = $currentDate+(60*30);
$formatDate = date("Y-m-d H:i", $futureDate);
when i debug $date i get the following result:
object(DateTime) {
date => '2013-03-08 05:54:00'
timezone_type => (int) 3
timezone => 'UTC'
}
i wish to extract date from this object. How do i do so?
solved it:
$currentDate = strtotime($date->format('Y-m-d H:i:s'));
but i still dont get it that why cant i use $date['date'], i mean $date like an array.
Related
I have an html table showing outage start and end times with different types of outages. Currently, I am sorting the outages in order of outage type, but I would like to be able to sort them by earliest to latest start times. The times in each start and end will already be in order, but I am trying to get them in order, regardless of type. I know for sorting by value, you usually use some sort of value compare like this "sort { $h{$a} <=> $h{$b} } keys(%h);"
Currently they sort like:
1 | phone | 00:00:00 | 04:08:03
2 | phone | 14:26:03 | 18:00:00
3 | television | 12:34:19 | 12:34:25
But it should be like:
1 | phone | 00:00:00 | 04:08:03
2 | television | 12:34:19 | 12:34:25
3 | phone | 14:26:03 | 18:00:00
This is my code.
my %outages;
my #outage_times = qw(start end);
my %outage_reasons = (
'tv' => 'television',
'p' => 'phone'
);
foreach my $outage_reason (values %outage_reasons) {
foreach my $outage (#outage_times) {
$outages{$outage_reason}{$outage} = [];
}
}
$outages{television}{start} = ['00:00:00', '14:26:03'];
$outages{television}{end} = ['04:08:03', '18:00:00'];
$outages{phone}{start} = ['12:32:02'];
$outages{phone}{end} = ['12:38:09'];
my $outage_number = 1;
foreach my $outage (sort keys %outages){
for my $i (0 .. scalar (#{$outages{$outage}{start}})-1) {
my $outage_start_time = $outages{$outage}{start}[$i];
my $outage_end_time = $outages{$outage}{end}[$i];
my $row_html = "<tr><td>$outage_number</td><td>$outage</td>";
$row_html .= "<td>$outage_start_time</td>";
$row_html .= "<td>$outage_end_time</td></tr>";
$outage_number += 1;
}
}
I think this is a situation where you are making life difficult for yourself because your data structure is unnecessarily complicated. I don't know where your data is coming from, but it would be far easier if you could get an array of hashes like this:
my #outages = ({
type => 'phone',
start => '00:00:00',
end => '04:04:03',
}, {
type => 'phone',
start => '14:26:03',
end => '18:00;00',
}, {
type => 'television',
start => '12:34:19',
end => '12:34:25',
});
The code to sort and print these then becomes almost trivial.
my $number = 1;
for (sort { $a->{start} cmp $b->{start} } #outages) {
my $row_html = '<tr>'
. "<td>$number</td>"
. "<td>$_->{type}</td>"
. "<td>$_->{start}</td>"
. "<td>$_->{end}</td>"
. "</tr>\n";
$number++;
print $row_html;
}
It's worth noting that this only works because your timestamps can be treated as strings which are easily sorted. If the timestamps were more complicated and included dates then you're probably going to want to convert them to sortable data using something like Time::Piece or DateTime.
I'd also mention that one day you'll discover that including raw HTML tags in your Perl code is a recipe for disaster. Far better to use a templating system like the Template Toolkit.
Don't store the time stamp as strings but as seconds-since-epoch. Then you can use normal numeric compare
foreach my $outage (sort { $a->{start} <=> $b->{start} values %outages) {
EDIT: SOP for time stamp processing in any language/program, unless you have some really out-of-this-world requirements:
parse the input format to convert time stamps to "X since epoch"
always convert to UTC, ie. determine time zone if it is not given
determine resolution (seconds, milliseconds, microseconds) provided by input
Date::Manip can be your friend here
process time stamps in your algorithm as numerical values
compare: a < b -> a happens before b
differences: a - b at your given resolution
convert timestamps to desired output format
if you have control of the output format, always opt for a precise format, e.g. use the UTC timestamp directly or ISO-8601 format
again Date::Manip::Date printf() method can be your friend here
In my Yii2 Project I have an array for example
$array = [];
$array [] = 8 , 3, 6
So when I print out the array is
[8,3,6]
So when I use the same in a where statement it jumbles up.
$class = ModelClass::find()->where(['array_no' => $array])->all
So when I print out class I get the output in asc order sorted..
I get the information of
3 in the first
6 in the second place
8 in the third place.
How can i stop this from happening. I want them to return my output in the same order as array
You should use ORDER BY FIELD(), e.g. :
$models = ModelClass::find()
->where(['array_no' => $array])
->orderBy(new \yii\db\Expression('FIELD (array_no, '.implode(',', $array).')'))
->all();
I like to sort my XML response.
This is my code:
// Make some cURL
// Create a simple XML element
$xml = new SimpleXMLElement($resp, LIBXML_NOWARNING, false);
// Output
foreach ($xml->Departure as $departure){
// DEFINE VARIABLES BASED ON XML RESPONSE
$name = $departure['name'];
$rtDate = $departure['rtDate'];
$rtTime = $departure['rtTime'];
$direction = $departure['direction'];
$trainCategory = $departure['trainCategory'];
// CALCULATE DURATION UNTIL NEXT DEPARTURE
$prognosedTime = new DateTime($rtTime);
$currentTime = new DateTime($time);
$interval = $currentTime->diff($prognosedTime);
// OUTPUT FOR BROWSERS
echo $interval->format('%i') . ' Min: ' . $name . ' > ' . $direction . '",';
echo $trainCategory;
echo "<hr/>";
};
?>
Result:
7 Min: Bus 240 > S Ostbahnhof
Bus
-------------------------------------
8 Min: Tram M10 > S+U Warschauer Str.
MetroTram
-------------------------------------
2 Min: U1 > Uhlandstr.
U-Bahn
-------------------------------------
0 Min: Tram M10 > S+U Hauptbahnhof
MetroTram
Problem:
My result should be sorted by $interval
I read
PHP sorting issue with simpleXML several times but I don't get it. So I wanted a shorter solution (for bloody beginners) and found something nice in Sort Foreach Loop after ID. But then I need arrays. Another solution is very close to that and shows how to define arrays: ASC sort foreach. But here I have no idea how to put all my data into an array as I never know how many rows the response will have. I believe I am very close to a solution but don't get it since 2 days. narf
How can i save date array to database?
the code belove creates a form for date
$form['date_time'] = array(
'#title' => t('Date'),
'#type' => 'date',
'#description' => t('Please enter the date.'),
);
User then selects the month,day,year.
How can i convert it so that i can save it to database?
function repman_form_submit($form, &$form_state){
drupal_set_message($form_state['values']['date_time']);
I am just using the drupal_set_message to view the output. And i get array.
UPDATE:
Done it using this
'date_month'=> $form_state['values']['date_time']['month'],
'date_day' => $form_state['values']['date_time']['day'],
'date_year'=> $form_state['values']['date_time']['year'],
You want to convert the date to ATOM or a unix timestamp:
// Dates are stored in ATOM format. 1969-12-31T19:33:33-05:00
$value = date(DATE_ATOM, mktime(0, 0, 0, $m, $d, $y));
// Convert to unix time
$value = date('U', mktime(0, 0, 0, $m, $d, $y));
I believe sql datetime uses ATOM but you can also stor it as a unix time stamp if you want to just stor it as an integer value.
I build a webshop, but the client wants a second currency, HKD. In the node-record.tpl.php file I found the line responsible for displaying the price:
print uc_currency_format($node->sell_price);
I looked into the Drupal documentation, and found the function currency_api_converter. To use it, I thought it should be like this:
print ' ('. currency_api_convert('RMB', 'EUR', $node->sell_price) .')</div>';
But for some reason, all I get is a sort of Array error:
What am I doing wrong?
Function currency_api_convert() returns array of values
$result['value'] = $value;
$result['rate'] = $rate;
$result['timestamp'] = $timestamp;
$result['date'] = $date;
$result['time'] = $time;
$result['status'] = TRUE;
$result['message'] = 'success';
Then you should to rewrite your code to
$convert = currency_api_convert('RMB', 'EUR', $node->sell_price);
print ' ('. $convert['value'] .' EUR)</div>';