从 Javascript 中的 YYYY-DD-MM 字符串中提取日、月、年

Extract day, month, year from a YYYY-DD-MM string in Javascript

我正在寻找从 Javascript 中 YYYY-DD-MM 的字符串中提取日、月、年的最佳解决方案:

摘自:

2019-25-01

要反对:

{ day: 25, month: 01, year: 2019 }

最好的方法是什么。提前致谢!

我会使用正则表达式 match 每个数字序列,将匹配的字符串数组映射到数字,解构为变量,然后从中创建一个对象:

const [year, day, month] = '2019-25-01'
  .match(/\d+/g)
  .map(Number);
const obj = { day, month, year };
console.log(obj);

请注意,数字不能有前导零。如果您希望月份有前导零,请改用字符串(只需删除 .map(Number))。

您可以拆分、解构和return一个新对象。

const getDate = string => (([year, day, month]) => ({ day, month, year }))(string.split('-'));

console.log(getDate('2019-25-01'));

你可以split()去做

var value = "2019-25-01";
var year = value.substring(0,4);
var day = value.substring(5,7);
var month = value.substring(8,10);
var str = "{day:" + day + ",month:" + month + ",year:" + year + "}";
console.log(str);

这是一个非常简短且快速的解决方案,仅适用于该格式和 ES6

function getJsonDate(text) {
  var {0: year, 1: day, 2: month } = text.split("-");
  return { day, month, year};
}
console.log(getJsonDate("2019-25-1"));

如果您需要字段为数字,则可以添加地图,如下所示:

function toNumber(text) {
  text = text - 0;
  return isNaN(text) ? 0 : text;
}
function getJsonDate(text) {
  var {0: year, 1: day, 2: month } = text.split("-").map(toNumber);
  return { day, month, year};
}
console.log(getJsonDate("2019-25-1"));

使用.split().

let date = "2019-25-01"
let dateArr = date.split('-')
let obj = {
  day: dateArr[1],
  month: dateArr[2],
  year: dateArr[0]
}
console.log(obj)

对于JSON类结构

d="2019-25-01";
x=d.split("-");
json="{ day: "+x[1]+", month: "+x[2]+", year: "+x[0]+" }";
>>"{ day: 25, month: 01, year: 2019 }"

这里有一种不需要映射 str -> array -> object 的方法,它将 string 直接转换为 object 并且也可以用于更通用的与时间约会。它基于可以在 String::replace()

上使用的 replacement 函数

const dateStr1 = "2019-25-01";
const dateMap1 = ["year", "day", "month"];
const dateStr2 = "2019-25-01 17:07:56";
const dateMap2 = ["year", "day", "month", "hour", "minute", "second"];

const splitDate = (str, map) =>
{
    let obj = {}, i = 0;
    str.replace(/\d+/g, (match) => obj[[map[i++] || i - 1]] = match);

    return obj;
}

console.log(splitDate(dateStr1, dateMap1));
console.log(splitDate(dateStr2, dateMap2));

另一种与您的日期格式密切相关的方式可能是下一个:

const strDate = "2019-25-01";

const splitDate = (str) =>
{
    let [date, year, day, month] = str.match(/(\d+)-(\d+)-(\d+)/);
    return {year, month, day};
}

console.log(splitDate(strDate));