Skip to content Skip to sidebar Skip to footer

Localizing Day And Month In Moment.js

How can I localize current day and month (without year) in moment.js? What I want is exactly the output of moment().format('LL') but without the year part. Consider the following e

Solution 1:

For error prone solution for all supported locales, you need to remove year with .replace and check for unnecessary symbols left:

functiongetCurrDayAndMonth(locale) {
  var today = locale.format('LL');
  return today
    .replace(locale.format('YYYY'), '') // remove year
    .replace(/\s\s+/g, ' ')// remove double spaces, if any
    .trim() // remove spaces from the start and the end
    .replace(/[рг]\./, '') // remove year letter from RU/UK locales
    .replace(/de$/, '') // remove year prefix from PT
    .replace(/b\.$/, '') // remove year prefix from SE
    .trim() // remove spaces from the start and the end
    .replace(/,$/g, ''); // remove comma from the end
}

['af' , 'ar-dz', 'ar-kw', 'ar-ly', 'ar-ma', 'ar-sa', 'ar-tn', 'ar', 'az', 'be', 'bg', 'bn', 'bo', 'br', 'bs', 'ca', 'cs', 'cv', 'cy', 'da', 'de-at', 'de-ch', 'de', 'dv', 'el', 'en-au', 'en-ca', 'en-gb', 'en-ie', 'en-nz', 'eo', 'es-do', 'es', 'et', 'eu', 'fa', 'fi', 'fo', 'fr-ca', 'fr-ch', 'fr', 'fy', 'gd', 'gl', 'gom-latn', 'he', 'hi', 'hr', 'hu', 'hy-am', 'id', 'is', 'it', 'ja', 'jv', 'ka', 'kk', 'km', 'kn', 'ko', 'ky', 'lb', 'lo', 'lt', 'lv', 'me', 'mi', 'mk', 'ml', 'mr', 'ms-my', 'ms', 'my', 'nb', 'ne', 'nl-be', 'nl', 'nn', 'pa-in', 'pl', 'pt-br', 'pt', 'ro', 'ru', 'sd', 'se', 'si', 'sk', 'sl', 'sq', 'sr-cyrl', 'sr', 'ss', 'sv', 'sw', 'ta', 'te', 'tet', 'th', 'tl-ph', 'tlh', 'tr', 'tzl', 'tzm-latn', 'tzm', 'uk', 'ur', 'uz-latn', 'uz', 'vi', 'x-pseudo', 'yo', 'zh-cn', 'zh-hk', 'zh-tw'].forEach(localeName => {
  console.log(
    localeName + ':',
    getCurrDayAndMonth(moment().locale(localeName)));
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>

Solution 2:

Do you just want the string representation? If so, it might be easier to just trim the last 5 chars from the end of the output, like so:

var today = moment().locale('tr').format('LL') // "1 Haziran 2017"
today = today.substring(0, today.length - 5); // "1 Haziran"

This'll work for the next 8000 years, so no real need to worry about future years breaking it.

You could even do smarter regex matching, or just remove everything with ", 20XX" from the string. Depends on your uses of it though, this is more of a hacky workaround than a direct solution.

Solution 3:

Here's an example of how it can work:

var d = moment().locale('tr');
console.log(d.format('D MMMM'));

JSFiddle: https://jsfiddle.net/webbm/wuwkwzou/

Post a Comment for "Localizing Day And Month In Moment.js"