React Native Get Current Date Time | Use of Moment for Date Time

How to get Current Date Time in React Native

This is an example, we will see how to get the current date-time in React Native using the Date function directly and using the moment.js which is very helpful when you deal with the date and time.

Moment.js is used to parse, validate, manipulate, and display dates and times in JavaScript

How to Get Current Date and Time using Date Function

To get the current date-time using Date function you just need to call it in the following ways

var date = new Date().getDate(); //To get the Current Date
var month = new Date().getMonth() + 1; //To get the Current Month
var year = new Date().getFullYear(); //To get the Current Year
var hours = new Date().getHours(); //To get the Current Hours
var min = new Date().getMinutes(); //To get the Current Minutes
var sec = new Date().getSeconds(); //To get the Current Seconds

How to Get Current Time using moment.js

var date = moment()
      .utcOffset('+05:30')
      .format('YYYY-MM-DD hh:mm:ss a');
  • moment() will return the current date-time
  • utcOffset is used to set your time zone
  • format will decide the output format
  • For Time Format:
    • Y/YYYY -> Year
    • M -> Month in single-digit(Ex. 8)
    • MM -> Month in double-digit(Ex. 08)
    • MMM -> Month short name (Ex. Aug)
    • MMMM -> Month full name (Ex. August)
    • D -> Day in single-digit(Ex. 5)
    • DD -> Day in single double-digit(Ex. 05)
    • HH -> Hours in 24 hr format
    • hh -> Hours in 12 hr format
    • mm -> Minutes
    • ss -> Seconds
    • a -> am/pm

You can use either Date function or moment.js to get the Date Time but as per my personal experience I would suggest using Date function while you are dealing in 24hr formate and if you are using 12hr (am/pm) format then go for moment.js. So let’s start with the example, we will see the one by one example for both.

First of all, you need to create a project

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

To get the Date Time Using Date Function

Open App.js in any code editor and replace the code with the following code.

App.js

/*This is an example of React Native Get Current Date Time*/
import React, { Component } from 'react';
import { StyleSheet, View, Alert, Text } from 'react-native';
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      //defauilt value of the date time
      date: '',
    };
  }
  componentDidMount() {
    var that = this;
    var date = new Date().getDate(); //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
      date:
        date + '/' + month + '/' + year + ' ' + hours + ':' + min + ':' + sec,
    });
  }
  render() {
    return (
      <View
        style={{
          flex: 1,
          justifyContent: 'center',
          alignItems: 'center',
        }}>
        <Text
          style={{
            fontSize: 20,
          }}>
          Current Date Time
        </Text>
        <Text
          style={{
            fontSize: 20,
            marginTop: 16,
          }}>
          {this.state.date}
        </Text>
      </View>
    );
  }
}

To Run the React Native App

Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

Output Screenshots

Output in Online Emulator

 

This is how you can get the date-time using Date function. Now to get the date-time using moment.js

To get the Date Time Using moment.js

To use moment you need to install moment dependency.

Installation of Dependency

To install this dependency open the terminal and jump into your project

cd ProjectName

Run the following commands

npm install moment --save

Open App.js in any code editor and replace the code with the following code

App.js

/*This is an example of React Native Get Current Time in 12 hours format AM PM*/
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import moment from 'moment';
//import moment to help you play with date and time

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      //defauilt value of the time
      time: '',
    };
  }
  componentDidMount() {
    var that = this;

    //Getting the current date-time with required format and UTC   
    var date = moment()
      .utcOffset('+05:30')
      .format(' hh:mm:ss a');

    that.setState({ time: date });
    //Settign up time to show
  }

  render() {
    console.log(this.state.totalDuration);
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text style={{ fontSize: 20 }}>{this.state.time}</Text>
      </View>
    );
  }
}

To Run the React Native App

Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

Output Screenshots

Output in Online Emulator

This is how you can get the current date and time using Date Function in 24hr format and using moment.js in 12hr format in React Native. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂


Related Posts

5 thoughts on “React Native Get Current Date Time | Use of Moment for Date Time”

    • Please update the following code in the example

      componentDidMount() {
        var monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May','Jun',
          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        var that = this;
        var date = new Date().getDate(); //Current Date
        var month = monthNames[new Date().getMonth()]; //Current Month
        var year = new Date().getFullYear(); //Current Year
      
        that.setState({
          //Setting the value of the date time
          date:
            date + '-' + month + '-' + year,
        });
      }
      Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.