0

I am facing an issue in javascript dates. I want to display previous and after 30min

How should I added previous or after 30min in current dates.

this.setState({
    current: new Date().toLocaleTimeString(), //10:30:02 PM
    slotTime: new Date().toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit'
    }), //10:30 AM

Output:

10:30 AM  //current date

expected:

10:00 AM   //previous
10:30 AM   //current
11:00 AM   //after 30min

anyone help me?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
MHasan
  • 69
  • 1
  • 8

2 Answers2

0

Hope this help

/* required:
  * - timestamp => number of timestamp format
  * - format => return format, ex. format 1 (23:59:59), format 2 (23:59)
  * return: time with string
  */
  function timestampToTime(timestamp, format = 1) {
    if (!isNaN(timestamp) || timestamp != undefined) {
      let dd = new Date(timestamp)

      if (format == 1) {
        return ('00' + dd.getHours()).slice(-2) + ':' + ('00' + dd.getMinutes()).slice(-2) + ':' + ('00' + dd.getSeconds()).slice(-2)
      } else if (format == 2) {
        return ('00' + dd.getHours()).slice(-2) + ':' + ('00' + dd.getMinutes()).slice(-2)
      }
    } else {
      return null
    }
  }

  let dd = + new Date()

  let previous = timestampToTime(dd - (1.8e+6))  // 1.8e+6 = 30 min
  let current = timestampToTime(dd)
  let after = timestampToTime(dd + (1.8e+6))  // 1.8e+6 = 30 min

  console.log(previous)
  console.log(current)
  console.log(after)
banguncool
  • 47
  • 7
  • it is too long can you make the logic short [@](https://stackoverflow.com/users/5515210/banguncool) – MHasan May 14 '20 at 07:14
  • There are a great many timestamp formats for which `isNaN(timestamp)` will return true. The OP is using Date objects so would probably prefer to keep working with Date objects. – RobG May 14 '20 at 07:23
0

You can simply do it like this:

var currDate = new Date();
var dd = new Date().setMinutes(currDate.getMinutes() - 30); //reduce 30 minutes
var ddPLus = new Date().setMinutes(currDate.getMinutes() + 30); //add 30 minutes

var reductedTime = new Date(dd);
var addedTime = new Date(ddPLus);

console.log("Current time: ", new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) //current time
console.log("Reduced time: ", reductedTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) // reduced time by 30mins
console.log("Added time: ", addedTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) // added time by 30mins
GoranLegenda
  • 491
  • 3
  • 9
  • You might consider using one Date object, then grabbing the "now" timestamp, subtract 30 minutes and get the earlier timestamp, then add an hour to get the later timestamp. :-) – RobG May 14 '20 at 07:26