Wednesday, May 29, 2019

React Native Create live Digital Clock using Local System Time

This tutorial explains how to create live digital clock and get current system time using local system time in react native. You may have seen this feature in your android or ios mobile lock screen and here we are going create similar implementation to get current system time in digital clock.

React Native Create live Digital Clock using Local System Time


React Native Create live Digital Clock Example :

Lets follow the below steps that helps to create live digital clock and get current system time using local system time in react native.



Step 1: Create a new react native project, if you don’t know how to create a new project in react native just follow this tutorial.

Step 2: Open App.js File in your favorite code editor and erase all code and follow this tutorial.

Step 3: Through react , react-native  packages import all required components.
import React, { Component } from 'react';
import { AppRegistry, View, Text, StyleSheet, Platform } from 'react-native';

Step 4: Lets create constructor block inside your App component.
constructor() {
    super();

    this.state = { currentTime: null, currentDay: null }
    this.daysArray = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
  }

Step 5: you need to implement componentWillMount  method.
componentWillMount() {
    this.getCurrentTime();
  }

Step 6: Lets create getCurrentTime function, which will helps to create formatted time and display in your android screen. 
  • Using new Date().getHours()  method, we can get current hour (0-23).
  • Using new Date().getMinutes()  method, we can get current minutes (0-59).
  • Using new Date().getSeconds()  method, we can get current seconds (0-59).
  • we are checking minutes < 10  and seconds < 10  condition because If minutes and seconds less than 10 then we have to add 0 as prefix to make our clock’s design more meaningful.
  • we are checking another condition hour > 12 because I want to create 12 hour digital clock.
  • Checking another important condition  new Date().getHours() < 12 because I want to show AM/PM as well.
  • Using new Date().getDay()  method, we can get the weekday in the form of number (0-6). 
getCurrentTime = () => {
    let hour = new Date().getHours();
    let minutes = new Date().getMinutes();
    let seconds = new Date().getSeconds();
    let am_pm = 'pm';

    if (minutes < 10) {
      minutes = '0' + minutes;
    }

    if (seconds < 10) {
      seconds = '0' + seconds;
    }

    if (hour > 12) {
      hour = hour - 12;
    }

    if (hour == 0) {
      hour = 12;
    }

    if (new Date().getHours() < 12) {
      am_pm = 'am';
    }

    this.setState({ currentTime: hour + ':' + minutes + ':' + seconds + ' ' + am_pm });

    this.daysArray.map((item, key) => {
      if (key == new Date().getDay()) {
        this.setState({ currentDay: item.toUpperCase() });
      }
    })
  }

Step 7: you need to implement componentWillUnmount and componentDidMount method.
 componentWillUnmount() {
    clearInterval(this.timer);
  }

  componentDidMount() {
    this.timer = setInterval(() => {
      this.getCurrentTime();
    }, 1000);
  }

Step 8: Implement render method inside the App class and wrapped the below layout design inside the root View component.
render() {

    return (
      <View style={styles.container}>
        <View>
          <Text style={styles.daysText}>{this.state.currentDay}</Text>
          <Text style={styles.timeText}>{this.state.currentTime}</Text>
        </View>
      </View>
    );
  }

Step 9 : Apply the below style sheet design.
const styles = StyleSheet.create(
  {
    container: {
      flex: 1,
      paddingTop: (Platform.OS === 'ios') ? 20 : 0,
      justifyContent: 'center',
      alignItems: 'center',
    },
    headerText: {
      fontSize: 30,
      textAlign: "center",
      margin: 10,
      color: 'black',
      fontWeight: "bold"
    },
    timeText: {
      fontSize: 50,
      color: '#f44336'
    },
    daysText: {
      color: '#2196f3',
      fontSize: 25,
      paddingBottom: 0
    }

  });


Complete Source Code for App.js 

Lets see the complete source code that helps to create live digital clock and get current system time using local system time in react native.

import React, { Component } from 'react';
import { AppRegistry, View, Text, StyleSheet, Platform } from 'react-native';

export default class App extends Component {

  constructor() {
    super();

    this.state = { currentTime: null, currentDay: null }
    this.daysArray = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
  }

  componentWillMount() {
    this.getCurrentTime();
  }

  getCurrentTime = () => {
    let hour = new Date().getHours();
    let minutes = new Date().getMinutes();
    let seconds = new Date().getSeconds();
    let am_pm = 'pm';

    if (minutes < 10) {
      minutes = '0' + minutes;
    }

    if (seconds < 10) {
      seconds = '0' + seconds;
    }

    if (hour > 12) {
      hour = hour - 12;
    }

    if (hour == 0) {
      hour = 12;
    }

    if (new Date().getHours() < 12) {
      am_pm = 'am';
    }

    this.setState({ currentTime: hour + ':' + minutes + ':' + seconds + ' ' + am_pm });

    this.daysArray.map((item, key) => {
      if (key == new Date().getDay()) {
        this.setState({ currentDay: item.toUpperCase() });
      }
    })
  }

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  componentDidMount() {
    this.timer = setInterval(() => {
      this.getCurrentTime();
    }, 1000);
  }

  render() {

    return (
      <View style={styles.container}>
        <View>
          <Text style={styles.daysText}>{this.state.currentDay}</Text>
          <Text style={styles.timeText}>{this.state.currentTime}</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create(
  {
    container: {
      flex: 1,
      paddingTop: (Platform.OS === 'ios') ? 20 : 0,
      justifyContent: 'center',
      alignItems: 'center',
    },
    headerText: {
      fontSize: 30,
      textAlign: "center",
      margin: 10,
      color: 'black',
      fontWeight: "bold"
    },
    timeText: {
      fontSize: 50,
      color: '#f44336'
    },
    daysText: {
      color: '#2196f3',
      fontSize: 25,
      paddingBottom: 0
    }

  });

Screenshot : 


React Native Create live Digital Clock using Local System Time

This is all about React Native Create live Digital Clock using Local System Time. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment