display day and month, without a year according to locale

前端 未结 4 604
灰色年华
灰色年华 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:39

    While the accepted answer does the job by manipulating the pre-defined localized formats Moment provides, there's another way that Moment allows you to extend its localized configuration that may be more suitable in some situations.

    If you open up one of the localization files in the npm module, like /moment/locale/de.js, you'll see a list of localized date formats that looks like this:

    longDateFormat : {
        LT: 'HH:mm',
        LTS: 'HH:mm:ss',
        L : 'DD.MM.YYYY',
        LL : 'D. MMMM YYYY',
        LLL : 'D. MMMM YYYY HH:mm',
        LLLL : 'ffffdd, D. MMMM YYYY HH:mm'
    },
    

    This will give you a good starting point and clue at how to localize for each locale you support. For example, German places the day with a period before the month, where in English, The month comes before the day.

    You can then copy and tweak the format you want, by extending the configuration at initialization:

    // Update configs with custom date formats per language after
    // moment locales are loaded (LMD is a custom format here)
    moment.updateLocale('en', { longDateFormat: { LMD: 'MMMM D' } });
    moment.updateLocale('de', { longDateFormat: { LMD: 'D. MMMM' } });
    // repeat with culturally-correct formatting for other locales you support
    
    function changeLang(value){
      moment.locale(value);
      
      // Retrieve stored custom format
      var format = moment.localeData().longDateFormat('LMD');
      var res = moment().format(format);
      
      $("#result").html(res);
    }
    
    
    
    
    
    

    You could also forego extending the configuration, and keep your custom formats in a custom data structure something like this:

    var MOMENT_FORMATS = {
      LMD: {
        en: 'MMMM D',
        de: 'D. MMMM'
      }
    };
    moment().format(MOMENT_FORMATS.LMD[moment.locale()])
    

提交回复
热议问题