display day and month, without a year according to locale

前端 未结 4 593
灰色年华
灰色年华 2020-12-12 03:17

Is there any better way for getting only day and month from a date including location appropriate separator?

I have a solution that gets separator first:

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 03:49

    As stated in the linked question: One way to do what you need is getting localized longDateFormat and then remove the year part with a regular expression.

    Daniel T. highlighted in comments that the solution will not work in locales like en-CA, so I'm going to provide an updated solution that takes in account some other locales that starts with year part.

    Probably there are some other locales the are not convered with /.YYYY/ and /YYYY./ RegExp, if you need to support every locale you can target them with ad hoc condition, as I made for ar-ly in the following snippet.

    Here a code sample the shows possible output in various locales:

    function changeLang(value){
      moment.locale(value);
      
      // Get locale data
      var localeData = moment.localeData();
      var format = localeData.longDateFormat('L');
      
      // Manage custom cases
      if( value === "ar-ly"){
        format = 'D/\u200FM';
      }
      // if( value === ...) possible othter cases
      
      // Check locale format and strip year
      if( format.match(/.YYYY/g) ){
        format = format.replace(/.YYYY/, '');
      }
      if( format.match(/YYYY./g) ){
        format = format.replace(/YYYY./, '');
      }
    
      var res = moment().format(format);
      
      $("#result").html(res);
    }
    
    
    
    
    
    

提交回复
热议问题