在moment.js中本地化日期和月份 [英] Localizing day and month in moment.js

查看:379
本文介绍了在moment.js中本地化日期和月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在moment.js中本地化当前日期和月份(无年份)?我想要的只是moment().format('LL')的输出,但没有年份部分.

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.

请考虑以下示例:

moment().locale('tr').format('LL') // "1 Haziran 2017"
moment().locale('en').format('LL') // "June 1, 2017"

我想要的是这些

moment().locale('tr').format('??') // "1 Haziran"
moment().locale('en').format('??') // "June 1"

推荐答案

对于所有受支持的语言环境的易于出错的解决方案,您需要使用.replace删除year并检查是否留有不必要的符号:

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

function getCurrDayAndMonth(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)));
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>

这篇关于在moment.js中本地化日期和月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆