Header Ads

Mastering Time Formats in MongoDB: A Comprehensive Guide

MongoDB is a powerful and flexible NoSQL database that has become a popular choice for modern web and mobile applications. One of the key features of MongoDB is its ability to handle time data effectively. Understanding how to work with time data is crucial for building robust applications that rely on time-based operations such as scheduling tasks, analyzing data trends, and creating reports.


In this article, we will explore the various time formats supported by MongoDB and how to work with them. We will cover the basics of time data, including how it is represented and stored in MongoDB, as well as advanced topics such as time zone handling, date arithmetic, and date aggregation. By the end of this article, you will have a solid understanding of how to work with time data in MongoDB and how to build applications that rely on time-based operations. So let's dive in!

MongoDB store dates in the ISODate format  

ISODate("2020-05-11T20:14:14.796Z")

but no one wants to display this form on his website or application!

The most used method to get the date in JavaScript is the new Date() object and pass your MongoDB time as a parameter :

let my_time = new Date(info.createdAt)

By default, when you run new Date()  your browser displays the date as a full-text string, like Fri Jul 02, 2023, 12:44:45 GMT+0100 (British Summer Time).

But having something like this on your web page or application is not professional and isn't easy to read. So this forces you to look for better ways to format these dates.

Let’s take a look at some methods that operate on a date object.

Date Methods in JavaScript

There are so many methods that you can apply to the date object. You can use these methods to get information from a date object.

 Here are some of them:

getFullYear() – gets the year as a four-digit number (yyyy)

getDate() – gets the day as a number (1-31)

getHours() – gets the hour (0-23)

getMonth() – gets the month as a number (0-11)
And lots more…

Unfortunately, most of these methods still need a lot of code to convert the dates to the format we desire.
For example, new Date().getMonth() will output 6 which stands for July. For me to use July in my project, I will need to have long code like this which can really be cumbersome:

 const currentMonth = new Date();
  const months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
  ];
  console.log(months[currentMonth.getMonth()]);



The toDateString() Method in JavaScript

The JavaScript toDateString() method returns the date portion of a date object in the form of a string using the following format:

First three letters of the weekday name
First three letters of the month's name
Two-digit day of the month, padded on the left a zero if necessary
Four-digit year (at least), padded on the left with zeros if necessary

  new Date().toDateString();
  //"Fri Jul 02 2023"


One major downside to this method is our inability to manipulate the date output the way we want it.
For example, it doesn’t give us the ability to show dates according to our language. Let’s take a look at another method which to me is still one of the best.

The toLocaleDateString() Method in JavaScript

This method returns the date object as a string using local conventions. It also takes in options as arguments that let you/your applications customize the behavior of the function.

const currentDate = new Date(info.createdAt);

  const options = { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric' };
 
  console.log(currentDate.toLocaleDateString('de-DE', options));
  //Freitag, 2. Juli 2023
 
  console.log(currentDate.toLocaleDateString('ar-EG', options))
  // الجمعة، ٢ يوليو ٢٠٢١
 
  console.log(currentDate.toLocaleDateString('en-us', options));
  //Friday, Jul 2, 2023

You can also decide not to use either locales or options:

  new Date(info.createdAt).toLocaleDateString()
// "7/2/2021

And you can also decide to only use locales. This will output the same information as the previous one based on my browser's time zone.


new Date(info.createdAt).toLocaleDateString('en-US')
"7/2/2021"


You can also decide to twist the options as you wish. There are 4 basic options which are:

  • weekday – This outputs the day of the week depending on how you want it to appear (short or long).
  • year – This outputs the year as a number
  • month – This outputs the month of the year depending on how you want it to appear (short or long).
  • day – Finally, this outputs the day as a number
 new Date(info.createdAt).toLocaleDateString("en-us", {
    weekday: "long",
    year: "numeric",
    month: "short",
  }); // "Jul 2021 Friday"

  new Date(info.createdAt).toLocaleDateString("en-us", {
    year: "numeric",
    month: "short",
  });
  // "Jul 2021"


Conclusion


The date object has about seven formatting methods. Each of these methods gives you a specific value:

  1. toString() gives you Fri Jul 02 2023 14:03:54 GMT+0100 (British Summer Time)
  2. toDateString() gives you Fri Jul 02 2023
  3. toLocaleString() gives you 7/2/2023, 2:05:07 PM
  4. toLocaleDateString() gives you 7/2/2023
  5. toGMTString() gives you Fri, 02 Jul 2023 13:06:02 GMT
  6. toUTCString() gives you Fri, 02 Jul 2023 13:06:28 GMT
  7. toISOString() gives you 2023-07-02T13:06:53.422Z

In conclusion, mastering time formats in MongoDB is essential for building robust applications that rely on time-based operations. Understanding how time data is represented and stored in MongoDB, and how to manipulate it, will help you create more efficient and effective applications. From basic date handling to advanced time zone management and date arithmetic, this guide has provided a comprehensive overview of working with time data in MongoDB. With this knowledge, you'll be well-equipped to tackle any time-based challenges in your MongoDB applications. Remember to always test and validate your code to ensure that your time data is accurate and reliable.


Time Formats in MongoDB
Time Formats in MongoDB





Fourni par Blogger.