简体   繁体   English

如何在 PHP 中定义我自己的日期格式?

[英]How can I define my own date format in PHP?

Could you clarify me, how can I define my own date format in PHP ?你能澄清一下,我如何在 PHP 中定义我自己的日期格式?

For instance, I have a date variable.例如,我有一个日期变量。

And I want to output this date as a date of the Ancient Roman calendar.我想将此日期输出为古罗马日历的日期。 Or in format of the French revolution calendar.或以法国大革命日历的格式。 These calendars, for example, begin not from the Christmas and have other names of months.例如,这些日历不是从圣诞节开始,而是有其他月份名称。

Also some calendars don't have weeks in 7 days, but have "weeks" in another quantity of days.此外,有些日历在 7 天内没有周,但在其他天数中有“周”。

Or in format as "year and season".或格式为“年份和季节”。 For example, "2016, the summer".例如,“2016,夏天”。

Is it possible to add a date format in PHP date formats and somehow code its output ?是否可以在 PHP 日期格式中添加日期格式并对其输出进行编码?

class MyDateTime extends DateTime {
      public string format ( $format ) {
             if ($format == "RD") { 
                //Convert to roman date
                return $romanDateFormat;

             }
             return parent::format($format);
      }

}

Then only use MyDateTime instead of DateTime然后只使用MyDateTime而不是DateTime

You can't directly add new format for the built-in DateTime object to handle as far as I know.据我所知,您不能直接为内置 DateTime 对象添加新格式来处理。

It's possible just define your own function.可以只定义自己的函数。 the way I think most poeple would do this is by create a functions.php file where your store your function and other custom functions.我认为大多数人会这样做的方式是创建一个functions.php文件,您可以在其中存储您的函数和其他自定义函数。 Then include functions.php in the file where you want to display roman date.然后在要显示罗马日期的文件中包含 functions.php。 Then declare your function :然后声明你的函数:

function translateToRomanCalendar($date = ""){//declare function

   $romanDate = "";//declare roman date variable

   //Put the translation code here. Using tests and stuff to store 
   //the  roman date  in the romanDate variable

   return $romanDate;//return the roman date

}

Then just call that function in your php file: for example to display the translated current year you would do然后只需在您的 php 文件中调用该函数:例如显示您将执行的翻译的当前年份

<?php echo translateToRomanCalendar(date('Y')) ?>

This will echo the return value of the function ($romanDate's value).这将回显函数的返回值($romanDate 的值)。

Now what will be tricky is the actual function's code;现在棘手的是实际函数的代码; you have to test for date format and stuff.你必须测试日期格式和东西。

anyways hope that helps there is tons of material on the web about php functions.无论如何,希望能有所帮助,网上有大量关于 php 函数的材料。

Regards问候

Alex亚历克斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM