Creating display date function in php, OOP way [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am beginning to learn PHP OOP and I have this exercise to create a a function displaying a date.
I would like to come up with this result:
$date = new ("14-01-2014"); // for example, this date from user
echo $date -> displaDate ('YYYY-MM-JJ'); // Would result to 2014-01-14
echo $date -> day; //Would result to 14
echo $date -> dayOfWeek; //Would result to Thursday
Can someone please explain to me how to start making a function for this? I understand that functions has variables and methods.

<?php
$dt = new DateTime();
echo $dt->format('j-n-Y');
?>

If you're into implementing it yourself, you could go by doing it this way:
class Date
{
private $KeysArray;
// Members
public $day;
public $dayOfWeek;
public function __constructor()
{
// 1) This should get the current date and save it in the "keys array":
// the constants should of course be replaced with the method you're using to get
// the year, month or whatever.
$this->KeysArray = array("YYYY" => YEAR_VALUE, "MM" = MONTH_VALUE...)
// 2) Set all of the properties (data members):
$this->day = DAY_VALUE
$this->dayOfWeek = DAY_OF_WEEK_VALUE
}
public function DisplayDate($DateFormatString)
{
// 1) Parse the $DateFormatString. Turn it into an array of the terms. If it's
// always going to be split with "-", then you could use the function
// "explode()".
// 2) Go over that array and try calling each item with the $this->KeysArray.
}
}

From version 5.2, PHP has DateTime class for the representation of date and time.
Eg.
$dateTime=new DateTime('NOW');
echo "<pre>";
print_r($dateTime);
echo "</pre>";
http://www.php.net/manual/en/class.datetime.php

It's simple....
<!DOCTYPE html>
<html>
<body>
<?php
$t=time();
echo($t . "<br>");
echo(date('Y-m-d',$t));
?>
</body>
</html>

#Daniel Saad, thank you for helping me understand. Here is the solution to my question:
class Date{
private $dateString;
function __construct( $dateString )
{
$this->dateString = $dateString;
}
// Method to display date in different formats.
public function displayDate( $dateFormat )
{
list( $day, $month, $year ) = explode( '-', $this->dateString);
switch($dateFormat)
{
case "YYYY-mm-dd" : $format = $year.'-'.$month.'-'.$day; break;
case "mm-dd-YYYY" : $format = $month.'-'.$day.'-'.$year; break;
default : $format = $year.'-'.$month.'-'.$day;
}
return $format;
}
//Method to get day
public function day()
{
$day = date('d', strtotime($this->dateString));
return $day;
}
//Method to get the day of the week.
public function dayofweek()
{
$weekday = date('l', strtotime($this->dateString));
return $weekday;
}
//Method to get month in text.
public function getmonth()
{
$month = date('F', strtotime($this->dateString));
return $month;
}
}
?>
index.php
<?php
//Initialisation
$date = new Date('14-01-2014');
$anotherdate = new Date('13-07-1979')
?>
<h3>Instance 1</h3>
<p>Date: <?php echo $date->displayDate('YYYY-mm-dd'); ?></p>
<p>Day: <?php echo $date->day(); ?></p>
<p>Day of week: <?php echo $date->dayofweek(); ?></p>
<p>Month: <?php echo $date->getmonth(); ?></p> <br />
Result:
Instance 1
Date: 2014-01-14
Day: 14
Day of week: Tuesday
Month: January
I hope this could also help those who are just beginning to understand OOP.

Related

Recursive object instantiation (in PHP)?

So in my PHP program I'm creating a calendar feature and one of the classes is "CalendarDay". What I want to do is be able to instantiate a new day for each day count, so for example new CalendarDay (22) means a new 22nd of the month date. There is also a show() function used for displaying each day. The class itself functions normally but when I try instantiating new days using recursion it no longer seems to work as everything related to the instantiated object disappears from the webpage.
class CalendarDay{
private $current_month;
private $current_year;
private $current_date;
public $reminderSet;
public $reminders;
public function __construct($current_day_of_month){
$current_year = date("Y");
$current_month = date("m");
$this->days_in_month = cal_days_in_month(CAL_GREGORIAN, $current_month, $current_year);
$this->current_date = date("d");
$this->current_day_of_month = $current_day_of_month;
}
public function show(){
$output = '<div class = "generator>"';
//$output .= $this->current_date;
//$output .= '<h1>' . $this->current_date . '</h1>';
$output .= '</div>';
$output .= $this->current_day_of_month;
echo $output;
}
}
My failed attempt at recursion:
for ($countTo31 == 0; $countTo31 == 31; $countTo31++){
$holder = $countTo31;
$date = new CalendarDay ($holder);
$date->show();
}
For the reference, this original block of code without the recursion works normally:
$holder = $countTo31;
$date = new CalendarDay ($holder);
$date->show();
I'm very confused with what you're trying to accomplish...
You have a "day" class which takes input to initialise a specific day but instead actually works out the current day based on date("Y-m-d");?.. And then outputs the input day anyway?
Honestly, it looks more like you want a "month" object
Initial problems
You use == to define your starting point
== is not an assignment operator, it's a comparison.
It effectively adds an additional iteration of the loop at the start of the loop
for($i == 1; $i < 5; $i++){
echo $i;
}
// Loop 1:
// --> Notice on $i == 1
// --> Notice on $i < 5
// --> Notice on echo $i
// --> Notice on $i++
// Loop 2:
--> $i = 1 BECAUSE of the previous $i++
so the intended loop starts...
Additionaly the loop, in this case, should start with 1 not 0(!)
You use == to define your condition
for loops like yours work effectively as:
for ( A ; B ; C ){
// Do something...
}
// Loop works as:
// Check A against B
// If TRUE then "Do something..."
// and then do C
// IF FALSE then break
However, even if your assignment (A) was correct (i.e. $countTo31 = 1), it still wouldn't work because 1 !== 31 and therfore the loop breaks from the start
It should be $countTo31 <= 31
Looping over object, rewriting the variable
Your code currently rewrites the variable which holds the date object with every loop
Effectively you create an object to output the day, output that data, and instantly remove the object so that it can't be used for anyting else...
Your HTML output has a " in the wrong place:
$output = '<div class = "generator>"';
//Should be...
$output = '<div class = "generator">';
Some of the variables in your class are not assigned or declared properly
$current_month is declared but never assigned
$current_year is declared but never assigned
$current_day_of_month is assigned but not declared
$days_in_month is assigned but not declared
Interim solution
Without further information on what you are intending to do it isn't possible to give good/accurate guidance, so I will leave a working example which should show you what to do:
$days_in_month = cal_days_in_month(
CAL_GREGORIAN,
date("m"),
date("Y")
);
for ($day = 1; $day <= $days_in_month; $day++){
echo "Day {$day}<br>";
}
Proposed changes
It doesn't look as though you really even want a "day" class for the functions you're trying to implement. So, in my mind, it would be better to first create a "month" object with all of the days of the month and then have that generate a "day" object for each day of the month which then can gather the information for each day e.g. reminders.
Doing it this way you can then update each day as you go with, for example, user input or database data.
class Month
{
private $month;
private $year;
private $days = [];
public function __construct($month, $year)
{
$this->month = $month;
$this->year = $year;
$number_of_days = cal_days_in_month(
CAL_GREGORIAN,
$month,
$year
);
for ($i = 1; $i <= $number_of_days; $i++){
$date = "{$this->year}-{$this->month}-{$i}";
// $days[] = new Day($date);
$this->days[$i] = new Day($date);
}
}
public function getDay($day)
{
return $this->days[$day];
}
public function getNumberOfDays()
{
return count($this->days);
}
}
class Day
{
private $date;
private $reminders = [];
public function __construct($date)
{
$this->date = $date;
// Initialise day...
# Get reminders
# Get meetings
# Get bills to pay
}
public function getReminders()
{
return $this->reminders;
}
public function setReminder($content, $time)
{
// Set reminders
$this->reminders[] = [
"content" => $content,
"time" => $time
];
}
public function show()
{
return date("d / m / Y", strtotime($this->date));
}
}
$month = new Month(12, 2020);
for ($i = 1; $i <= $month->getNumberOfDays(); $i++){
echo $month->getDay($i)->show()."<br>";
}

Undefined offset (in function)

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

Calculate date before n days of a month

How to calculate a date before 10 days of every month end ?Am using codeigniter platform.
I need to check whether a date is within 10 days before the end of every month.
Please help
You can try using date_modify function for example see this php documentation
http://php.net/manual/en/datetime.modify.php
i need to check whether a date is within10 days before the end of a month
function testDate($date) {
$uDate = strtotime($date);
return date("m", $uDate) != date("m", strtotime("+10 days", $uDate));
}
echo testDate("2016-03-07") ? "Yes" :"No"; // No
echo testDate("2016-03-27") ? "Yes" :"No"; // Yes
you can create a library with this
class Calculate_days{
function __construct() {
parent::__construct();
}
function calculate( $to_day = date("j") ){
$days_month = date("t");
$result = (int) $days_month - $to_day;
if( $result <= 10){
$result = array("type" => TRUE, "missing" => $result . 'days');
return $result;
}
else{
$result = array("type" => FASLE, "missing" => $result . 'days');
return $result;
}
}
}
controller.php
function do_somthing(){
$this->load->library('Calculate_days');
$result = $this->Calculate_days->calculate(date("j"));
var_dump($result);
}

php add method incorrectly working

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')

PHP if based on current system date

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

Categories