我开始学习PHP OOP,我有一个练习来创建一个显示日期的函数。 我想得出这个结果: $ date = new(“14-01-2014”); //例如,来自用户的这个日期
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
有人可以向我解释如何开始为此制作功能吗?我知道函数有变量和方法。
答案 0 :(得分:1)
<?php
$dt = new DateTime();
echo $dt->format('j-n-Y');
?>
答案 1 :(得分:0)
从版本5.2开始,PHP具有DateTime
类用于表示日期和时间。
例如
$dateTime=new DateTime('NOW');
echo "<pre>";
print_r($dateTime);
echo "</pre>";
答案 2 :(得分:0)
如果你自己实施它,你可以这样做:
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.
}
}
答案 3 :(得分:0)
这很简单......
<!DOCTYPE html>
<html>
<body>
<?php
$t=time();
echo($t . "<br>");
echo(date('Y-m-d',$t));
?>
</body>
</html>
答案 4 :(得分:0)
@Daniel Saad,谢谢你帮助我理解。以下是我的问题的解决方案:
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 />
<强>结果:强> 实例1 日期:2014-01-14 第14天 星期几:星期二 月:1月
我希望这也可以帮助那些刚刚开始理解OOP的人。