【问题标题】:How can I change a date string into words in Laravel? [duplicate]如何在 Laravel 中将日期字符串更改为单词? [复制]
【发布时间】:2020-04-21 17:04:51
【问题描述】:

我有一个像04-01-1965 这样的日期,我想把它改成这样的词:Fourth January Nineteen Sixty Five

我如何在 Laravel 中做到这一点?

【问题讨论】:

  • 其中一些可以使用 carbon.nesbot.com/docs/#api-formatting 完成,但我认为年份部分可能有点棘手
  • 碳提供Thursday 25th December 1965 和我想要的不一样。
  • PHP 和 Laravel/Carbon 都不会开箱即用。您将不得不为它创建自己的解决方案。

标签: php laravel laravel-blade


【解决方案1】:

Laravel 和 PHP 都不会给你这种输出。您必须为此编写自己的代码。在这种情况下,你可以试试这个:

$th = array( 
1 => "first", 2 => "second", 3 => "third", 4 => "fourth", 5 => "fifth", 6 => "sixth", 
7 => "seventh", 8 => "eighth", 9 => "nineth", 10 => "tenth", 11 => "eleventh", 12 => "twelfth", 13 => "thirteenth", 14 => "fourteenth", 15 => "fifteenth", 16 => "sixteenth", 17 => "seventeenth", 18 => "eighteenth", 19 => "nineteenth", 20 => "twentyth" 
); 

$ones = array( 
1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five", 6 => "six", 
7 => "seven", 8 => "eight", 9 => "nine", 10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen", 
14 => "fourteen", 15 => "fifteen", 16 => "sixteen", 17 => "seventeen", 18 => "eighteen", 19 => "nineteen" 
); 

$tens = array( 
1 => "ten",2 => "twenty", 3 => "thirty", 4 => "forty", 5 => "fifty", 
6 => "sixty", 7 => "seventy", 8 => "eighty", 9 => "ninety" 
); 

$dateString = "04-01-1965";

$day = date("j", strtotime($dateString));
if ($day <= 20) $day = $th[$day];
if($day > 20 ){
    $day = strval($day);
    $second = intval($day[1]);
    $str1 = $tens[intval($day[0])];
    $str2 = $th[intval($day[1])];
    $day = $str1." ".$str2;
}

$month = date("F", strtotime($dateString));
$year = strval(date("Y", strtotime($dateString)));

$first_half = intval($year[0].$year[1]);
if($first_half < 20 ) $first_half = $ones[$first_half];
// Updated
if($first_half >= 20) {
    if($year[1] == '0')
       $first_half = $tens[$year[0]];
    else 
       $first_half = $tens[$year[0]]." ".$ones[$year[1]];
}

$second_half = intval($year[2].$year[3]);
if($second_half < 20 ) $second_half = $ones[$second_half];
if($second_half >= 20) {
   $second_half = $tens[$year[2]]." ".$ones[$year[3]];
}

$years = $first_half." ".$second_half;
echo "Today is " . $day." ".strtolower($month)." ".$years."<br>";

它会给你这样的输出:Today is fourth january nineteen sixty five

【讨论】:

  • Undefined offset: 0 on $first_half = $tens[$year[0]]." ".$ones[$year[1]]; 输入 25-04-2020 但可以使用 $dateString = "04-01-1965";
  • 我已经更新了代码。并请一个建议。别介意。试着理解每一行代码。只是不要复制和粘贴。你不能这样学习。谷歌更多。 Undefined offset error有很多解决方案。
猜你喜欢
  • 2017-02-18
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 2017-06-07
  • 2011-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多