skip to Main Content

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

4

Answers


  1. 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" 
    Login or Signup to reply.
  2. You can use slice.

    let time_start = "2022-12-22 14:56:00"
    console.log(time_start.slice(11,-3))
    //Output: 14:56
    
    Login or Signup to reply.
  3. 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'),
    
      }
    })
    
    
    
    Login or Signup to reply.
  4. 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>
                  ))
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search