-2

I have a problem. I have a json in and inside this is a string with the format dd.mm.yyyy. I would like to output within a loop for each month, once only the day, the day and the month and the complete date. Unfortunately, if I write it as I am doing right now. I get 1527 displayed.

How do I get the day, month, and complete date back in a loop?

// import React, { useState, useEffect } from 'react'

function Test() {
  const days = [
    "Januar",
    "Februar",
    "März",
    "April",
    "Mai",
    "Juni",
    "Juli",
    "August",
    "September",
    "Oktober",
    "November",
    "Dezember",
  ];
  const matchDays = [
    { date: new Date('12.05.2022') },
    { date: new Date('01.06.2027') },
  ];
  return (
    <div>
      {
        days &&
        <ul class="days">
          {
            days.map((d, i) =>
              <li>
                { d }
                <span class="dates">
                  {
                    matchDays.map((d, i) =>
                      <span class="date"> { d.date.getDate() } </span>
                    )
                  } 
                </span>
              </li>
            )
          }
        </ul>
      }
    </div>
  );
}

// export default Test
ReactDOM.render(<Test/>, document.querySelector("#test"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="test"></div>

Desired output

12 
12.05
12.05.2022
01
01.06
01.06.2027
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
Test
  • 571
  • 13
  • 32
  • 1
    Can you provide an example of the output format you want to achieve? – Dean James May 22 '22 at 09:15
  • 1/2 ... It is always nice to either provide running example code in form of a stack snippet especially if it comes to DOM render task or provide a boiled down version of the code. Especially for the OP's problem a good approach which mostly works is to take a step back and separate the data transformation process (e.g. filtering / mapping / reducing ) from UI related ones. One gets a more clear view at the problem due to e.g. faster iteration based on better testing possibilities (here unit tests for the data layer). – Peter Seliger May 22 '22 at 10:16
  • 2/2 ... Secondly the OP does not work upon JSON. [`JSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) is a string based standardized data interchange format and a JavaScript namespace with static methods. But the OP wants to iterate an array and a not even JSON conform data-structure. – Peter Seliger May 22 '22 at 10:22
  • 3/3 ... and what is the `days` array and also iterating it good for, if none of its items is part of the desired output? And regarding the output ... since each date apparently should just be rendered twice partially and once in its German locale string form why does the OP not provide the `date` directly as string and just splits it like e.g. ... `'12.05.2022'.split(''.)`? – Peter Seliger May 22 '22 at 10:33
  • 1
    Re `new Date('12.05.2022')`, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG May 23 '22 at 09:00

2 Answers2

0

From my above comments ...

"1/2 ... a good approach which mostly works is to take a step back and separate the data transformation process (e.g. filtering / mapping / reducing ) from UI related ones. One gets a more clear view at the problem due to e.g. faster iteration based on better testing possibilities (here unit tests for the data layer)."

"3/3 ... regarding the output ... since each date apparently should just be rendered twice partially and once in its German locale string form why does the OP not provide the date directly as string and just splits it like e.g. ... '12.05.2022'.split(''.)?"

Thus said, each simplified date-item from an array like ...

const matchDays = [
  { date: '12.05.2022' },
  { date: '01.06.2027' },
];

... will be mapped into an array of date parts based on simply splitting and partially rejoining it.

const matchDays = [
  { date: '12.05.2022' },
  { date: '01.06.2027' },
];

const renderData = matchDays
  .map(({ date }) => {
    const [day, month] = date.split('.');

    return [day, [day, month].join('.'), date];
  });

console.log({ renderData });
.as-console-wrapper { min-height: 100%!important; top: 0; }

Based on the above example code a 2nd refactoring step would change the pure data mapping into a combined data/UI render task.

// import React, { useState, useEffect } from 'react'

function Test() {
  const matchDays = [
    { date: '12.05.2022' },
    { date: '01.06.2027' },
  ];
  return (
    <ul class="date-items">
      {
        matchDays.map(({ date }) => {
          const [day, month] = date.split('.');
          return (
            <li>
              <ul class="date-partials">
                <li>{ day }</li>
                <li>{ [day, month].join('.') }</li>
                <li>{ date }</li>
              </ul>
            </li>
          )
        })
      }
    </ul>
  );
}

// export default Test
ReactDOM.render(<Test/>, document.querySelector("#test"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="test"></div>
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
-1

You can simply iterate over matchDays and render 3x elements with each part:

  return (
    <ul>
      {matchDays.map((day) => (
        <>
          <li>{day.date.getDate()}</li>
          <li>
            {day.date.getDate()}.{day.date.getMonth() + 1}
          </li>
          <li>
            {day.date.getDate()}.{day.date.getMonth() + 1}.{day.date.getFullYear()}
          </li>
        </>
      ))}
    </ul>
  );

Each <li> contains either day, day & month, or day & month & year. Note that I've used <li> here as an example - choose what you need in your app.

Result:

  • 1
  • 1.10
  • 1.10.2002
  • 5
  • 5.11
  • 5.11.2022
  • 27
  • 27.1
  • 27.1.2022

Edit: Fixed month +1 to avoid 0 based value.

Dean James
  • 2,491
  • 4
  • 21
  • 29
  • @Test ... 1/2 ... Even in case one fixes the source of the syntax error(s) of the above provided code, the numbers of the rendered date partials are getting displayed without leading zeros ... compare `'5.12.2022'` versus the OP's request of `'12.05.2022'`. – Peter Seliger May 22 '22 at 19:00
  • @Test ... 2/2 ... But more importantly, casting a dot separated date-string of the `dd.mm.yyyy` form like `'12.05.2022'` into a `new Date` leads to _**Monday the 5th December 2022**_ but not to _**Thursday the 12th of May 2022**_ like intended, and thus rendering it with `Date` methods results in wrong/misleading date strings anyhow. Then the Q. remains ... why was this in many ways wrongly implemented solution upvoted and accepted by the OP? – Peter Seliger May 22 '22 at 19:00
  • 1
    @PeterSeliger—unfortunately the person asking the question is often the least qualified to determine the best answer. If they weren't, they likely wouldn't have asked in the first place. Hence votes. ;-) – RobG May 23 '22 at 09:02
  • Boy did this get a lot of attention. The question asked is `How do I get the day, month, and complete date back in a loop?` and that is answered above. Yes, the leading zeros issue is not provided, but any reasonable person can see that isn't the point of interest. I'm also confused about the point made around month/day vs day/month formats, considering the OP only lists an input format of `dd.mm.yyyy` in the `matchDays` array. I think the main difference between the two answers here is one is simple and one is more scalable and thus more complex, and neither are strictly incorrect. – Dean James May 23 '22 at 10:04