Ding0
Ding0

Reputation: 305

Getting the current time in correct format - React-Native

I can get the Date function directly using moment.js but when the minutes are under 10 it will not display the 0.

Please see picture below for example.

enter image description here

the time is meant to be 12:02 and 12:03

constructor(props) {
      super(props);
      this.state = {
        datetimefinish: '',
      };
    }


  componentDidMount() {
      var that = this;
      var date = new Date().getDate('0' + Number()); //Current Date
      var month = new Date().getMonth() + 1; //Current Month
      var year = new Date().getFullYear(); //Current Year
      var hours = new Date().getHours(); //Current Hours
      var min = new Date().getMinutes(); //Current Minutes
      var sec = new Date().getSeconds(); //Current Seconds

      that.setState({
        //Setting the value of the date time
        datetimefinish:
           hours + ':' + min
      });
    }

<Text style={styles.text}>{this.state.datetimefinish}</Text>

Upvotes: 3

Views: 1145

Answers (3)

vincenzopalazzo
vincenzopalazzo

Reputation: 1645

You can try this code and parse the string is you need some substring value

var time = new Date();

document.getElementsByTagName("p")[0].innerHTML=time.toTimeString().substring(0, 5);
<p id="time"> </p>

In your case you can use this code

<Text style={styles.text}>{this.state.time.toTimeString().substring(0, 5)}</Text>

An example can be this TimeZone app

Upvotes: 0

LyonsTheWay2Gold
LyonsTheWay2Gold

Reputation: 373

Please try this if using moment.js to get the Date Time

componentDidMount() {
 var that = this;
 var date = moment()
.format(' HH:mm');
that.setState({ datetime: date });}

Upvotes: 3

Wellington J&#250;nior
Wellington J&#250;nior

Reputation: 264

You can resolve with this:

...
that.setState({
        datetimefinish:
           `${("0" + hours).slice(-2)}:${("0" + min).slice(-2)}`
      });
...

Upvotes: 0

Related Questions