Home > database >  How to display only a certain part from Json data in React.js
How to display only a certain part from Json data in React.js

Time:12-22

I wrote the code like below and show like photo.

enter image description here

but

I want to show only "hour and minutes" like

14:56

Is it possible to display only hours and minutes like this? If it is possible, how can I show it?

Json

    {     
        "time_start": "2022-12-22 14:56:00",
        "time_end": "2022-12-22 16:56:00",
    }

React.js

              {schedules.map(schedule => (
                <div className="each_scheduled" key={schedule.id}>
                  <div>
                  <p className="scheduled_p">Time</p>
                  <p className="scheduled_p">{schedule.time_start} - {schedule.time_end}</p>
                  </div>
                </div>
              ))}

CodePudding user response:

You can use slice.

let time_start = "2022-12-22 14:56:00"
console.log(time_start.slice(11,-3))
//Output: 14:56

CodePudding user response:

I don't know if that's the best approach, but you can split the date from the time like this:

let time_start = "2022-12-22 14:56:00"

time_start = time_start.split(" ")

time_start[1] = time_start[1].substring(0, time_start[1].length-3);

console.log(time_start[1])
//Output: "14:56" 

CodePudding user response:

I would strongly advice you to work with a library dedicated for dates and times, it will make your life a lot easier, I highly suggest luxon

with which your code could then look like so:

// const { DateTime } = require('luxon')
// or with imports:
import { DateTime } from 'luxon'


// ... code ...

const times = schedules.map(schedule => {
  return {
    start: DateTime
          .fromFormat(schedule.time_start, 'yyyy-MM-dd HH:mm:ss')
          .toFormat('HH:mm'),
    end: DateTime
          .fromFormat(schedule.time_end, 'yyyy-MM-dd HH:mm:ss')
          .toFormat('HH:mm'),

  }
})


CodePudding user response:

If the format of your time strings is fixed, you could use the slice() function to slice the strings at appropriate indexes.

Changing your code as follows will achieve the desired result:

{schedules.map(schedule => (
                <div className="each_scheduled" key={schedule.id}>
                  <div>
                  <p className="scheduled_p">Time</p>
                  <p className="scheduled_p">{schedule.time_start.slice(11, 16)} - {schedule.time_end.slice(11, 16)}</p>
                  </div>
                </div>
              ))
}

  • Related