Hello Friends đź‘‹,

Welcome To Infinitbility! ❤️

To get the current datetime in react native has the Date() object it will return every time the current date and time when we use it.

we have to just write new Date() and it returns the date object where we get a year, month, date, hours, minutes, and seconds.

let today = new Date();
console.log(today); // 2022-02-06T08:05:49.292Z

Now, we know we have the current date time but we can’t show the same to also users.

To format, we have multiple packages like Day.js, and Moment.js.

But if wanna follow a custom formater follow the below code.

Let see how we can show current time in react native.

import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';

export default function App() {
  const [time, setTime] = useState(null);

  useEffect(() => {
    let time = getCurrentTime();
    setTime(time);
  }, []);

  const getCurrentTime = () => {
    let today = new Date();
    let hours = (today.getHours() < 10 ? '0' : '') + today.getHours();
    let minutes = (today.getMinutes() < 10 ? '0' : '') + today.getMinutes();
    let seconds = (today.getSeconds() < 10 ? '0' : '') + today.getSeconds();
    return hours + ':' + minutes + ':' + seconds;
  }

  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>{'Current time'} - {time}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Output

React Native, current, time, example
React Native, get current time example.

In above example, we are extracting and formating new Date() to time in React Native.

Try it yourself

Thanks for reading…