Moment.js 解析字符串+格式化
Moment.js解析字符串+格式化 用于通过给定的格式字符串解析日期字符串。解析器会忽略格式中的非字母数字字符。它将解析后的日期作为Moment对象返回。
语法:
moment(String, String, Boolean);
参数: 此方法接受三个参数,如上所述,并在下面进行了描述:
- String: 这是要解析的日期字符串。
- String: 这是用于解析日期的格式。
- Boolean: 它指定是否使用严格解析。
返回值: 此函数将解析后的日期返回为Moment对象。
注意: 在普通的Node.js程序中,这不起作用,因为需要安装moment.js库。
可以使用以下命令安装Moment.js:
npm install moment
示例1: 获取日期作为输出。
const moment = require("moment");
let date = moment("01-11-2022", "MM-DD-YYYY");
console.log("The date is", date);
输出:
The date is Moment<2022-01-11T00:00:00+05:53>
示例2: 解析器默认忽略非字母数字字符。
const moment = require("moment");
let date = moment("2022/12/01", "YYYY-MM-DD");
console.log("The date is", date);
输出:
The date is Moment<2022-12-01T00:00:00+05:30>
参考: https://momentjs.com/docs/#/parsing/string-format/