I get this error in my dates function
when my in panel this code calls the function fecha,only when it calls the date it throws the error, the status and the amount, if it appears to me.
<h1>Viendo compra de <span style="color:#08f"><?=$nombre?></span></h1><br>
Fecha: <?=fecha($r['fecha'])?><br>
Monto: <?=number_format($r['monto'])?> <?=$divisa?><br>
Estado: <?=estado($r['estado'])?><br>
here is the function
<?php
function fecha($fecha){
$e = explode("-",$fecha);
$year = $e[0];
$month = $e[1];
$e2 = explode(" ",$e[2]);
$day = $e2[0];
$time = $e2[1];
$e3 = explode(":",$time);
$hour = $e3[0];
$mins = $e3[1];
return $day."/".$month."/".$year." ".$hour.":".$mins;
}
?>
You need not to reinvent bicycle, just use PHP built in functions:
<?php
function fetcha($originalDate) {
return date("d/m/Y H:i", strtotime($originalDate));
}
echo fetcha('2020-12-06 10:11:12');
Test PHP code here
Related
How can i sum times into array using Carbon?
<?php
namespace App\Models;
use Carbon\Carbon;
class Appointment extends BaseModel
{
public static function total_time()
{
$appointments = Appointment::get();
$sumtimes = [];
foreach($appointments as $a){
$dti = Carbon::parse($a->dateinitial);
$dtf = Carbon::parse($a->datefinal);
$time = $dti->diff($dtf)->format('%H:%I:%S');
$sumtimes[] = $time;
}
$sumtimes= sum($sumtimes);
return $sumtimes;
}
inside sum_times, there is a list of times that need to be summed like:
$sum_times[0] = "00:01:18"
$sum_times[1] = "00:03:11"
$sum_times[2] = "01:01:18"
$sum_times[3] = "00:01:28"
I need it to return "01:07:15"
<?php
public static function total_time(): string
{
$seconds = 0;
foreach(Appointment::get() as $appointment){
$dateinitial = Carbon::parse($appointment->dateinitial);
$datefinal = Carbon::parse($appointment->datefinal);
$seconds += $datefinal->diffInSeconds($dateinitial);
}
return gmdate('H:i:s', $seconds);
}
Also you must set for your fields (dateinitial, datefinal) cast datetime for automated parsing to Carbon type. Docs for date casts.
Each result of diff can be continuously added to a datum. At the end of the loop we get the sum as the difference from the base date to the date. Carbon is an extension of DateTime. I show the sample code with the base class so that it is reproducible for everyone.
$data = [
['from' => '2022-03-01 16:00', 'to' => '2022-03-02 12:00'], //20:00:00
['from' => '2022-03-02 12:30', 'to' => '2022-03-02 22:02'], //09:32:00
]; //total 29:32:00
$basis = '2000-01-01';
$dateBase = date_create('2000-01-01');
$date = clone $dateBase;
foreach($data as $dates){
$dateFrom = date_create($dates['from']);
$dateTo = date_create($dates['to']);
$diff = $dateFrom->diff($dateTo);
$date->add($diff);
}
$totalDiff = $dateBase->diff($date);
$hours = $totalDiff->d *24 + $totalDiff->h; //days * 24 + hours
echo 'Sum: '.$hours.$totalDiff->format(':%I:%S');
//Sum: 29:32:00
Try self on 3v4l.org
I want to give an alert when a condition is met in a day time, right now I get the hours statically
$hour1 = strtotime ("09:00");
$hour2 = strtotime ("01:00");
but I want to get the established schedule from the DB
$hour1 = strtotime ("09:00");
$hour2 = strtotime ("01:00");
if ($hour1 > $hour2) {
Session::flash('message', 'ABIERTO!');
Session::flash('', '');
}
elseif ($hour1 < $hour2 ) {
Session::flash('message', 'SHOP CLOSED!');
Session::flash('alert-class', 'alert-danger');
}
I already created the model on table status
help pls
You can try like this
$hour1 = DateTime::createFromFormat('H:i', $status->open);
$hour2 = DateTime::createFromFormat('H:i', $status->closed);
OR just simply
$hour1 = new DateTime($status->open);
$hour2 = new DateTime($status->closed);
Then just make conditional
if ($hour1 > $hour2)
// what to do
I'm in the process of learning PHP and i'm having some trouble. My function is returning the "milestones" with the same date they were plugged in with. I believe I am using the add() method incorrectly. Thankyou.
PHPplayground: http://www.tehplayground.com/#cARB1wjth
$milestones = null;
$milestones = createMilestone($milestones, true, 10, "15-1-1", "birthday" );
var_dump( $milestones );
function createMilestone($milestones, $forward, $days, $startDate, $milestoneName ){
if ( is_string($startDate)){
$date = DateTime::createFromFormat("Y-m-d", $startDate );
}else if(is_array($startDate) ){
$date = $startDate["date"];
}else{
$date = $startDate;
};
$daysInterval = DateInterval::createFromDateString($days);
if ($forward){
$date->add($daysInterval);
}else{
$date->sub($daysInterval);
}
$milestones[$milestoneName]['date'] = $date;
return $milestones;
}
You need to use :
$daysInterval = DateInterval::createFromDateString($days . ' days');
See the doc here for DateInterval and that page for the diverse date formatting (called relative format) you can use.
And BTW, if you give a DateTime like "15-1-1", the correct format is not "Y-m-d" but "y-m-d" (lowercase 'y')
Trying to setup a page that auto updates based on the users date/time.
Need to run a promotion for 2 weeks and each day it needs to change the displayed image.
Was reading through http://www.thetricky.net/php/Compare%20dates%20with%20PHP to get a better handle on php's time and date functions.Somewhat tricky to test, but I basically got stuck on:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date() = $dateA){
echo 'todays message';
}
else if(date() = $dateB){
echo 'tomorrows message';
}
?>
I know the above function is wrong as its setup, but I think it explains what I am aiming for.
Time is irrelevant, it needs to switch over at midnight so the date will change anyway.
You seem to need this:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date('Y-m-d') == $dateA){
echo 'todays message';
} else if(date('Y-m-d') == $dateB){
echo 'tomorrows message';
}
?>
you want
<?php
$today = date('Y-m-d')
if($today == $dateA) {
echo 'todays message';
} else if($today == $dateB) {
echo 'tomorrows message';
}
?>
I would go a step back and handle it via file names. Something like:
<img src=/path/to/your/images/img-YYYY-MM-DD.jpg alt="alternative text">
So your script would look something like this:
<img src=/path/to/your/images/img-<?php echo date('Y-m-d', time()); ?>.jpg alt="alternative text">
If you're going to do date calculations, I'd recommend using PHP's DateTime class:
$promotion_starts = "2012-07-16"; // When the promotion starts
// An array of images that you want to display, 0 = the first day, 1 = the second day
$images = array(
0 => 'img_1_start.png',
1 => 'the_second_image.jpg'
);
$tz = new DateTimeZone('America/New_York');
// The current date, without any time values
$now = new DateTime( "now", $tz);
$now->setTime( 0, 0, 0);
$start = new DateTime( $promotion_starts, $tz);
$interval = new DateInterval( 'P1D'); // 1 day interval
$period = new DatePeriod( $start, $interval, 14); // 2 weeks
foreach( $period as $i => $date) {
if( $date->diff( $now)->format("%d") == 0) {
echo "Today I should display a message for " . $date->format('Y-m-d') . " ($i)\n";
echo "I would have displayed: " . $images[$i] . "\n"; // echo <img> tag
break;
}
}
Given that the promotion starts on 07-16, this displays the following, since it is now the second day of the promotion:
Today I should display a message for 2012-07-17 (1)
I would have displayed: the_second_image.jpg
This is part of an events page that can be filtered by date (using pre-defined date ranges or a date picker).
I want to avoid repeating the whole foreach ($days as $day_number)... etc. loop for every condition.
I guess that whole loop could be moved to a function, but I'm not sure how to implement it.
<?php
// open the db connection
$db = new wpdb('user', 'pass', 'db', 'server');
// $today = date('Y-m-d');
$today = '2009-06-21';
$tomorrow = date( 'Y-m-d', mktime(0, 0, 0, date('m'), date('d')+1, date('Y')) );
$seven_days_ahead = date( 'Y-m-d', mktime(0, 0, 0, date('m'), date('d')+6, date('Y')) );
$thirty_days_ahead = date( 'Y-m-d', mktime(0, 0, 0, date('m'), date('d')+29, date('Y')) );
echo '<div class="column first">';
if ( ! empty($_REQUEST['date_range']) )
{
// user has chosen a date/range, show matching events
$date_range = mysql_real_escape_string($_REQUEST['date_range']);
switch( $date_range )
{
case 'all':
// code here
break;
case 'next_7_days':
// code here
break;
case 'next_30_days':
// code here
break;
default:
// code here
}
}
else
{
// no date selected, show todays events
$days = convert_date_to_day_number( $today );
foreach ( $days as $day_number )
{
$where = sprintf( 'WHERE e.day_id = %s', $day_number );
$events = get_events( $where );
if ($events)
{
echo '<table class="results">';
render_day( $day_number );
foreach ($events as $event)
{
render_event($event);
}
echo '</table>';
}
else
{
echo 'No events';
}
}
}
echo '</div> <!--/column-->';
function convert_date_to_day_number($date)
{
global $db;
$sql = "SELECT day_number FROM days WHERE day_date = '$date'";
$day_numbers = $db->get_results($sql);
foreach ($day_numbers as $key => $value)
{
$day_number[] = $value->day_number;
}
return $day_number;
}
function get_events($where)
{
global $db;
$sql = "SELECT
e.id,
TIME_FORMAT(e.start_time, '%H:%i' ) AS start_time,
e.x_prod_desc AS title,
-- e.title_en AS title,
p.name_en AS place,
et.name_en AS type,
w.week_number,
d.day_date AS start_date
FROM event AS e
LEFT JOIN place AS p ON p.id = e.place_id
LEFT JOIN event_type AS et ON et.id = e.event_type_id
LEFT JOIN days AS d ON d.id = e.day_id
LEFT JOIN week AS w ON w.id = d.week_id ";
$sql .= $where;
$events = $db->get_results($sql);
return $events;
}
function render_event($event)
{
$request_uri = $_SERVER['REQUEST_URI'];
$output = <<<EOD
<tr class="week-$event->week_number">
<td class="topic"></td>
<td class="time">$event->start_time</td>
<td class="summary">
$event->title
</td>
<td class="type">$event->type</td>
<td class="location">
<span class="addr">$event->place</span>
</td>
</tr>
EOD;
echo $output;
}
function render_day( $day_number )
{
global $db;
$sql = "SELECT
d.day_number,
DATE_FORMAT( d.day_date, '%W %e %M %Y' ) AS date,
DATE_FORMAT( d.day_date, '%b' ) AS month,
DATE_FORMAT( d.day_date, '%e' ) AS day
FROM days AS d
WHERE day_number = " . $day_number;
$day = $db->get_results($sql);
$day = $day[0];
$output = <<<EOD
<tr class="day">
<th colspan="5">
<em class="date">
<abbr class="dtstart" title="20090605T1806Z">
<span title="$day->date">
<span class="month">$day->month</span>
<span class="day">$day->day</span>
</span>
</abbr>
</em>
$day->date
<span class="event-day">Day $day->day_number</span>
</th>
</tr>
EOD;
echo $output;
}
?>
First, you may want to use strtotime for relative dates :
$today = '2009-06-21';
$tomorrow = date( 'Y-m-d', strtotime('+1 day') );
$seven_days_ahead = date( 'Y-m-d', strtotime('+7 days') );
$thirty_days_ahead = date( 'Y-m-d', strtotime('+30 day') );
// or +1 month (=> calendar month)
Second, you can set two variables with begin & end dates, then:
$date = $start_date; // 'Y-m-d' format
while( $date <= $end_date ) {
//code here or fill up a table with your days
// using $date
$date = date( 'Y-m-d', strtotime( '+1day', strtotime($date) ) );
}
Whenever working with dates in PHP, you should check strtotime.
Rather than querying the database once for every day, I would make a WHERE statement that fetched all events for the desired date range, and then send that to a render function which loops through every row in the result set and if the day is different from previous one, calls render_day() before calling render_event().
switch (/* input from user */) {
// Build a date range here.
// Resulting statement would be something like:
// WHERE event_date >= '2009-06-10' AND event_date < '2009-06-17'
}
$events = get_events($filter);
$prev_date = null;
foreach ($events as $event) {
if ($event->date != $prev_date) render_day($event->date);
render_event($event);
$prev_date = $event->date;
}
function generateEventsTable($dateStr)
{
$days = convert_date_to_day_number( $today );
foreach ( $days as $day_number )
{
$where = sprintf( 'WHERE e.day_id = %s', $day_number );
$events = get_events( $where );
if ($events)
{
echo '<table class="results">';
render_day( $day_number );
foreach ($events as $event)
{
render_event($event);
}
echo '</table>';
}
else
{
echo 'No events';
}
}
}
Call it like this:
generateEventsTable($today);
Wow! I've read it!
First of all use template engine (like smarty) or any other way to split your code and HTML. That's a bad idea to echo HTML from inside the functions.
I'm not sure but I think that using unix-timestamps in DB could simplify your data structure. The same is about php code. Read carefully about date/time functions in php manual, I think, you'll find a lot of interesting things...
Actually, as I see from your code using timestamps and templates will reduce your code to some line for fetching data and assigning it to template engine. PHP's "date()" function already has an option to return week numbe, day number in a week or in a year etc...
This is dummy exaple what could your code look like:
$begin = mktime(...);
$end = mktime(...);
$query = "
SELECT a,b,c
FROM events
WHERE ctime >= $begin AND ctime <= $end AND ...
";
$events = array();
while ($fetch = fetch_here(...))
{
$event = new MyEvent();
$event->loadDBFetch($fetch);
array_push($events, $event);
}
$tplEngine->assign('events', $events);
Sure, this is not a ready-to-go solution, but it seems to me, that your code could be similar to this.