即时获取时间段AM // PM已本地化

时间:2019-06-14 05:41:06

标签: javascript momentjs

我们是否有像moment.weekdays()moment.months()这样的函数会返回本地化的AM PM?像moment.period()一样?

timeFormatDefaultLocale({
    "dateTime": "%A, der %e. %B %Y, %X",
    "date": "%d.%m.%Y",
    "time": "%H:%M:%S",
    "periods": ["AM", "PM"], <------ I need to pass moment function to get period
    "days":  moment.weekdays() as any,
    "shortDays": moment.weekdaysShort() as any,
    "months": moment.months() as any,
    "shortMonths": moment.monthsShort() as any
});

2 个答案:

答案 0 :(得分:1)

请尝试使用

 moment.format('A') 

这里A是AM PM格式

请参阅下面的示例:

  console.log('Current Time is :'+moment().format('hh:mm A')) ;
   
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
 
 

答案 1 :(得分:0)

没有内置的momentjs函数来使['AM', 'PM']本地化,如果您查看文档的Accessing locale specific functionality部分,您会看到此刻具有isPM和{{1} }:

meridiem

请查看Customize#AM/PMCustomize#AM/PM Parsing部分,以获取有关瞬间如何管理子午线的更多信息。

对于大多数语言环境,您可以编写自己的解决方法函数(使用moment(Object)format()locale()),如下所示:

localeData = moment.localeData()
// ...
localeData.isPM(amPmString);  // returns true iff amPmString represents PM
localeData.meridiem(hours, minutes, isLower);  // returns am/pm string for particular time-of-day in upper/lower case
// ...
function period(locale) {
  return [
    moment({h: 0}).locale(locale).format('A'),
    moment({h: 23}).locale(locale).format('A')
  ];
}

['en', 'en-us', 'de', 'it', 'fr', 'zh-cn'].forEach(localeName => {
  console.log( localeName, period(localeName) );
});

如果您还需要管理具有多个AM / PM值(例如<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>)的语言环境,则可以使用以下内容:

zh-cn
function period(locale) {
  const result = new Set();
  let m = moment({h: 0}).locale(locale);
  for(let i=0; i<24; i++) {
    result.add( m.format('A') );
    m.add(1, 'h');
  }
  return Array.from(result);
}

['en', 'en-us', 'de', 'it', 'fr', 'zh-cn'].forEach(localeName => {
  console.log( localeName, period(localeName) );
});


如果您考虑使用其他库,请注意,Luxon(momentjs “弟弟” )具有Info.meridiems()方法,即使您似乎总是能够处理, 2个AM / PM值(请参见<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>结果):

zh-cn
const Info = luxon.Info;

['en', 'en-us', 'de', 'it', 'fr', 'zh-cn'].forEach(localeName => {
  console.log( localeName, Info.meridiems({ locale: localeName }) );
});