skip to Main Content

I have the problem for this situation. I want to print like console.log did in the screen for react nativeenter image description here

`

const dString = text;
  const days = 30;

  let [day, month, year] = dString.split('/');

  // month - 1 as month in the Date constructor is zero indexed
  const now = new Date(year, month - 1, day);
  let loopDay = now;
  for (let i = 0; i <= days; i++) {
    loopDay.setDate(loopDay.getDate() + 6);
    console.log ('Day: ' + loopDay);
  }

here’s my code and I want to print in return of function in react-native so result of looping can show on my screen`

2

Answers


  1. One way you could do this is by adding all the loop days to an array like so:

    To increase the date you can multiply by i to increase the offset.

    const loopDays = [];
    const now = new Date(year, month - 1, day);
    for (let i = 0; i <= days; i++) {
      const loopDay = new Date(now);
      loopDay.setDate(loopDay.getDate() + 6 * (i + 1));
      console.log("Day: " + loopDay);
      loopDays.push(loopDay);
    }
    

    And the you can display them by looping over the loopDays like so

    return (
      <View>
        {loopDays.map((day) => {
          return <Text>Day: {day}</Text>;
        })}
      </View>
    );
    
    Login or Signup to reply.
  2. Solution :

    import {View,Text} from 'react-native';
    
    export default function App() {
    
      const ShowDates = () => {
        const dString = '29/10/2022';
        const days = 30;
    
        let [day, month, year] = dString.split('/');
    
        // month - 1 as month in the Date constructor is zero indexed
        const now = new Date(year, month - 1, day);
        let loopDay = now;
    
        let tempArray = [];
      
        for (let i = 0; i <= days; i++) {
          loopDay.setDate(loopDay.getDate() + 6);
          tempArray.push(loopDay);
        } 
    
        return tempArray;
      } 
    
      return (
        <View style={{flex:1,justifyContent:'center',alignItems:'center',paddingTop:30}}>
        {ShowDates()?.map((item,index)=>(
          <Text key={index}>Day : {item.toLocaleString()} </Text>
        ))}
        </View>
      );
    }
    
    

    Solution Image

    Hope it helps 😊

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search