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

How to format user input into the correct localized format?

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

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

我正在尝试关注 these guidelines in order to use a local moment

// 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() 应该 return null 或抛出错误或任何我不介意的东西。

我尝试了 localLocale(userInput) 但它抛出了一个 localLocale is not a function

语言环境集是您定义的时刻实例的本地设置。所以

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

localLocale 的本地设置为 'fr'。因此,如果您只想针对此输入在本地执行此操作,您可以使用:

// 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>

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

If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.

你可以用moment.ISO_8601, as shown , to parse ISO 8601 inputs as moment(String)做。

请注意moment(String, String[])

Starting in version 2.3.0, Moment uses some simple heuristics to determine which format to use. In order:

  • Prefer formats resulting in valid dates over invalid ones.
  • Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.
  • Prefer formats earlier in the array than later.

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

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>