No need for external libraries, as React Native fully supports JavaScript’s Date functionalities. Simply create a new Date object to capture the current date and time:
let currentDate = new Date(); console.log(currentDate);
Customize further by specifying options like language and time zone:
let currentDate = new Date(); console.log(currentDate.toLocaleDateString()); // prints date in the format: "MM/DD/YYYY" console.log(currentDate.toLocaleTimeString()); // prints time in the format: "HH:MM:SS AM/PM"
When dealing with intricate date calculations or crafting custom date displays, you might find libraries like moment.js and date-fns useful companions.
Here’s how you can get the current date with moment.js:
import moment from 'moment'; let currentDate = moment().format('YYYY-MM-DD'); console.log(currentDate);
For projects prioritizing efficiency, day.js stands out as a compelling alternative to moment.js. While sharing similar functionality, its reduced footprint makes it a top contender for performance-hungry environments.
Here’s how you can get the current date with day.js:
import dayjs from 'dayjs'; let currentDate = dayjs().format('YYYY-MM-DD'); console.log(currentDate);
For simple date tasks, the built-in Date object is good enough. But in larger projects, where date acrobatics and fancy formatting are needed, libraries like moment.js and date-fns come to the rescue. And for those extra concerned about app size and speed, day.js is gaining a lot of love for being small and similar to moment.js. Think of it as the lightweight, high-performance option for your date with code!