1

I am facing an issue with javascript dates. I want to change the format of date

        this.setState({ 

          current: Date(Date.now()),



      }, 1000);


//convert minutes 
//if minutes are 0 to 29 then show current hours reset the minutes again start with 0 like 18:00 
//if minutes are 29 to 59 then show current hours reset the minutes again start with 30 like 18:30

var slotTime1 = currentdate.getHours() +':'+ (currentdate.getMinutes() <= 29 ? '00' : '30') ;  //10:30

Output:

Thu May 14 2020 10:00:30 GMT+0500 (Pakistan Standard Time)

Expected

10:00:52 AM
10:30 AM

What should I change?

batman567
  • 642
  • 1
  • 5
  • 17
adnan khan
  • 81
  • 1
  • 6
  • Use [Intl.DateTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat). – Ben Aston May 14 '20 at 05:41
  • When called as a function, *Date* doesn't take any arguments and returns a string representing the current date and time. So in `Date(Date.now())`, the argument is redundant, the expression produces the exact same result as `Date()`. – RobG May 15 '20 at 20:22

2 Answers2

1

You can simply use Date toLocaleTimeString() method like:

const current = new Date()
const timestring = current.toLocaleTimeString()
console.log( timestring )   //=> 10:47:52 AM

The toLocaleTimeString() method returns a string with a language sensitive representation of the time portion of the date.


To only get hh:mm a format you can pass option object to the toLocaleTimeString() method like:

const current = new Date()
const timestring = current.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
console.log( timestring )   //=> 10:50 AM

With setState:

this.setState({
  current: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
});
palaѕн
  • 64,836
  • 15
  • 100
  • 121
0
var date=new Date();    
console.log(date.getHours() + ":" + date.getMinutes()+ ":" + date.getSeconds() + " " + date.getHours()<12 ? 'AM' : 'PM'}`);

OUTPUT : 11:9:37 AM

date.getHours()<12 results in AM between 12Am to 11:59 AM and after 11:59 it results in PM

Raman Sharma
  • 171
  • 2
  • 10
  • 1
    `date.getHours() < 12? 'AM' : 'PM'` is a lot less to type and more semantic. Also you should pad the minutes and seconds to two digits. ;-) – RobG May 15 '20 at 20:27