如何将用户输入格式化为正确的本地化格式



我有一个<input type="text"/>,用户可以(尝试(以任何格式/语法键入日期(即使是无效格式(。

我想得到用户输入的任何内容的值,通过本地化的时刻传递它,然后用正确的格式更新输入。

为了使用本地时刻,我正在努力遵循这些指南

// I want to use a local instance of moment
let localLocale = moment();
// I want to set the locale to be 'fr'
localLocale.locale('fr')
// I want to set the format to be 'LL'
localLocale.format('LL')
// this is what the user typed in
let userInput = '2/3/1986'
// I want to do:
let formattedUserInput = something(userInput)

formattedUserInput的值必须是Mars 2, 1986

我正在寻找something应该是什么。目前文档非常混乱,无法解释如何做到这一点。

如果userInput明显是胡言乱语,那么something()应该返回null或抛出错误或其他我不介意的东西。

我试过localLocale(userInput),但它抛出了localLocale is not a function

您可以使用moment(String, String[])来解析不同格式的输入:

如果您不知道输入字符串的确切格式,但知道它可能是许多字符串中的一个,则可以使用格式数组。

您可以使用moment.ISO_8601,如图所示,像moment(String)一样解析ISO 8601输入。

请注意moment(String, String[])

从版本2.3.0开始,Moment使用一些简单的启发式方法来确定使用哪种格式。按顺序:

  • 比起无效日期,更喜欢产生有效日期的格式
  • 更喜欢解析更多字符串而不是更少,使用更多格式而不是更少的格式,即更喜欢更严格的解析
  • 首选数组中较早的格式而不是较晚的格式

一种可能的解决方案如下:

function something(userInput){
let m = moment(userInput, [moment.ISO_8601, 'DD/MM/YYYY', 'MM/DD/YYYY' ]);
if( !m.isValid() ){
// throw "Invalid input";
}
return m.locale('fr').format('LL');
}
['2/3/1986', 'aaa', '10-15-2017'].forEach((userInput) => {
console.log( something(userInput) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/locale/fr.js"></script>

区域设置是您定义的即时实例的本地设置。所以

let localLocale = moment();
localLocale.locale('fr');

将CCD_ 13的本地设置为CCD_。因此,如果您只想在本地进行此输入,您可以使用:

// this is what the user typed in
let userInput = '2/3/1986';
// Use a local instance of moment, using the user's input
let localLocale = moment(userInput, 'D/M/YYYY');
// Set the locale to be 'fr'
localLocale.locale('fr');
// Get the formatted string
let formattedUserInput = localLocale.format('LL');
console.log(formattedUserInput);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment-with-locales.min.js" integrity="sha256-VrmtNHAdGzjNsUNtWYG55xxE9xDTz4gF63x/prKXKH0=" crossorigin="anonymous"></script>

最新更新