I guess this is quite simple question, but I am currently unable to find it in moment's documentation. I have to display just an hour in local format, e.g.
en-gb
: 14en-us
: 2 PMThe closest format I've found is LT
, but it also displays minutes that are not desired...
Here is what I tried:
moment().format('LT'); // 14:00 / 2:00 PM
// I need some kind of combination of these two:
moment().format('H'); // 14
moment().format('h A'); // 2 PM
Is there a moment-way to achieve it or am I forced to use a work-around like below?
moment().format('LT').replace(/:[0-9]{2}/, '');
There is no built-in method in momentjs 2.18.1 to get the localized input you are looking for. The localized formats availables that include time are:
Time | LT | 8:30 PM
Time with seconds | LTS | 8:30:25 PM
Month name, day of month, day of week, year, time | LLLL | Thursday, September 4 1986 8:30 PM
| llll | Thu, Sep 4 1986 8:30 PM
So you probably have to use a work around like you showed in the question. The following script creates and displays a Map with the number of occurences for each LT
string. It uses localeData
and longDateFormat
to get localized format for LT
.
let formatMap = new Map();
['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 => {
var format = moment.localeData(localeName).longDateFormat('LT');
if( formatMap.has(format) ){
let val = formatMap.get(format);
formatMap.set(format, val+1);
} else {
formatMap.set(format, 1);
}
});
console.log(formatMap);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>
Note that breton (br
) locale uses h[e]mm A
format and there are 7 locales (including: German (Switzerland) de-ch
, Finnish fi
, Indonesian id
, etc) that use HH.mm
.
Those cases are not covered by your workaround, maybe you can use something like:
moment().format('LT').replace(/(:|\.)[0-9]{2}/, '');
or
moment().format('LT').replace(/(:|\.|e)[0-9]{2}/, '');
to get the desired output for these locales.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With