【问题标题】:How I can put dates in two category Spring and Fall?如何将日期分为春季和秋季两类?
【发布时间】:2015-03-30 07:56:25
【问题描述】:

如何将日期分为春季和秋季两类??

我在表格中有这样的日期

2012-08-27 
2011-01-12 
2011-08-27  
2010-01-12
2010-08-27
2009-01-12
2009-08-27

当我从表中检索它们时,我需要将它们设置为“SPRING 2010”、“Fall 2010”

27 日总是意味着秋天,12 日总是意味着春天

我需要提取年份并检查它是秋季还是春季并输出“SPRING 2010”、“Fall 2010”

请帮忙看看如何做到这一点?谢谢。

【问题讨论】:

  • substr($date, -2) 将包含 27 或 12

标签: php date


【解决方案1】:
$string = '2012-08-27'; // your initial string

$year = substr($string,0,4); //$year = '2012'
$season = (substr($string,-2)=='27' ? 'FALL' : 'SPRING'); //$season = 'FALL'
$full = $season.' '.$year; //$full = 'FALL 2012'

echo $full; //will output 'FALL 2012'

//as a function
function season_year($n){
    //if 27 = fall
    #return ((substr($n,-2)=='27' ? 'FALL' : 'SPRING').' '.substr($n,0,4));
    //if 27 = spring
    return ((substr($n,-2)=='27' ? 'SPRING' : 'FALL').' '.substr($n,0,4));
}

【讨论】:

  • 非常感谢,这非常有效。你能告诉我如何扭转它吗?例如,如果给定的字符串是“Fall 2012”,那么 27 日总是意味着 FALL,而 12 日总是意味着 SPRING
  • 查看我的编辑 - 我注释掉了原来的并添加了替代。
【解决方案2】:

您可以遍历日期并使用explode 来提取日期。

foreach($dates as $date){

 list($year,$month,$day) = explode('-', $date)
 if($day == '27'){
   $season = 'FALL '.$year;
 }else{
   $season = 'SPRING '.$year;
 }

【讨论】:

    【解决方案3】:

    使用mysql你可以这样做

    select 
     case 
       when day(date_field) = '27' then concat('Fall',' ',year(date_field))
       when day(date_field) = '12' then concat('Spring',' ',year(date_field))
     end as `display`
    from table_name
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      • 2015-08-31
      相关资源
      最近更新 更多