Reputation: 10240
I am trying to use the toTimeString() method to display the time in the following format
13:45 (No Seconds, No timezone)
What I reeeeeeally would like to do is hack the function to display only the hours and the minutes in separate <span></span>
so that I can add the :
blinking inside it as a regular clock would.
I did this for jQuerty sites, AngularJS, Typescript(Angular2), but I can't figure out how to do it in React
This is my component right now
import React from 'react';
import {Link, hashHistory} from 'react-router';
import FlatButton from 'material-ui/FlatButton';
import 'jquery-slimscroll/jquery.slimscroll.min';
class SidebarContent extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
render() {
return (
<ul className="nav" ref={(c) => { this.nav = c;}}>
<li className="city-row" ref="cityRow">
<p>{this.state.date.toTimeString('en-US', { hour12: false }).replace(/.*(\d{2}:\d{2}:\d{0}).*/, "$1")}</p>
<p>{this.state.date.toDateString()}</p>
</li>
...
nav stuff in here
...
</ul>
);
}
}
module.exports = SidebarContent;
This gets me this output 13:45:
Close, but not quite. I can't get rid of the trailing colon and if I take it out the hours dissapear instead of the seconds. Just a hot mess
How can I manipulate the toTimeString Method to display the hh only, and then the MM only in a separate <p> or <span>
?
If you have any other way to do this without toTimeString(), I'm open to it as long as it uses react LifeCycle and all the bells and whistles. (No sloppy hacks, please)
Here is a CODEPEN to mess around with the toTimeString() Method
Thanks in advance
Upvotes: 1
Views: 1102
Reputation: 3267
Building of Abdennours answer I've written the following because I had 2 times I wanted to format, and it also solved the problem where a time on the hour showed as :0
rather than :00
toTimeString(date: Date) {
return date.getHours() + ':' + date.getMinutes().toString().padStart(2, "0");
}
Upvotes: 0
Reputation: 93203
If you have any other way to do this without toTimeString()
Yes , there is getHours
and getMinutes
. You can use them directly :
var n = d.getHours() + ':'+ d.getMinutes();
getTime() {
return this.state.date.getHours() + ':' + this.state.date.getMinutes() ;
}
render() {
return (
<ul className="nav" ref={(c) => { this.nav = c;}}>
<li className="city-row" ref="cityRow">
<p>{this.getTime()}</p>
<p>{this.state.date.toDateString()}</p>
</li>
...
nav stuff in here
...
</ul>
);
}
Upvotes: 2