最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin11PV0评论

I am finding the best solution for extracting day, month, year from string with YYYY-DD-MM in Javascript:

Extract from:

2019-25-01

To object:

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

What is the best way to do it. Thank in advance!

I am finding the best solution for extracting day, month, year from string with YYYY-DD-MM in Javascript:

Extract from:

2019-25-01

To object:

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

What is the best way to do it. Thank in advance!

Share Improve this question edited Sep 13, 2020 at 21:38 Nina Scholz 387k26 gold badges363 silver badges412 bronze badges asked Jan 25, 2019 at 10:40 KitKitKitKit 9,51315 gold badges64 silver badges89 bronze badges 4
  • 3 Surely you have tried some coding already to solve this problem. Please show us what you have tried so far. – Tim Biegeleisen Commented Jan 25, 2019 at 10:42
  • 1 @Cid: This is not one of the supported formats for Date.parse; so, not a dupe (as it requires further steps). – Amadan Commented Jan 25, 2019 at 10:43
  • @Amadan ah, true, thanks for pointing me that. I didn't notice the date is in a stupid format, un-sortable and so on. – Cid Commented Jan 25, 2019 at 10:45
  • @Cid: Stupid or not, it's official in three countries. – Amadan Commented Jan 25, 2019 at 10:45
Add a comment  | 

7 Answers 7

Reset to default 21

You could split, destructure and return a new object.

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

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

I'd use a regular expression to match each number sequence, map the array of matched strings to numbers, destructure into variables, then create an object from it:

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

Note that numbers cannot have leading zeros. If you want the month to have a leading zero, use a string instead (just remove the .map(Number)).

This is a pretty short and fast solution that will only work for that format and in ES6

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

If you need the fields to be numbers then you can add a map, like so:

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"));

You can split()to do it

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);

Use .split().

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

For JSON like structure

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

Here you have one approach that don't need to do the mapping str -> array -> object, it will convert the string directly to object and can be used also for a more generalized date with time. It is based on the replacement function that can be used on String::replace()

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));

Another way that is strictly related to your date format could be next one:

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));

Post a comment

comment list (0)

  1. No comments so far