DEV Community

Cover image for Everything you need to know about Date in Programming
shrey vijayvargiya
shrey vijayvargiya

Posted on • Updated on

Everything you need to know about Date in Programming

The only guide you need to deal with dates in programming.

Under the Hood

The story begins for my website content, iHateReading. I was thinking about topics I should cover in programming.

The idea that came to my mind is to cover some interview topics along with explanations and make the blog interesting.

I was preparing for an interview and google the javascript methods on the array and read one blog on medium covering details about javascript array methods such as filter, map and reduce. That single blog made me understand the JS methods very well and is something I want to follow today to understand everything about dates in JavaScript.

Date

Date is a type of data in programming or can be called as it is used to manage data or time-effective data.

In JavaScript, dates are represented using the Date object, which provides methods for creating and manipulating dates and times.

The Date Object:

In JavaScript, the Date object is the go-to solution for handling dates and times. It allows you to create new data instances and perform various operations, such as retrieving the current date and time, extracting specific components like the year, month, or day, and performing calculations based on dates.

The date is used in various formats in programming

  • Storing user date-related information, such as birth dates
  • Calculate the time elapsed
  • Comparing 2 entities based on time
  • Data management along with filtering, sorting, and reducing are done using data

A lot of use cases can be seen to date in programming but the important thing is how javascript deals with data.

Javascript provides a date constructor or class, so since it’s a class we can only invoke it using a new keyword.

If it's a constructor date = new Date()
If it's a method date = date.method()
If it's a property date = date.property
Enter fullscreen mode Exit fullscreen mode

We can access javascript available resources such as method, property and constructor using the above notation.

Since the date is a constructor we will use the notation number one.

const date = new Date()
and this way of using date is called a simple date constructor.

There is another way to use a date is using a specific date and time.

const specificDate = new Date(2023, 9, 26, 12, 0, 0, 0);

Enter fullscreen mode Exit fullscreen mode

Over here the params passed to the date constructor are the month, year, date, hour, minute, second and milliseconds.

The same pattern of passing params is used in developing time-based APIs such as scheduling a tweet, scheduling an email and so on.

node.cron(function sendEmail() => {}, 2023, 10, 27, 0, 0, 0)

This means my node.js server or javascript method will schedule 
the method sendEmail at 30th October 2023 during 0 hour,0 minute 
and 0 second and 0 millisecond
Enter fullscreen mode Exit fullscreen mode

Date Constructor

This is important because no dates can be parsed or constructed in JavaScript without a date constructor.

Since it’s a class/constructor, we will use a new keyword every time we want to use it.

const date = new Date()
Enter fullscreen mode Exit fullscreen mode

Every class object in javascript has 3 thing

  • Params
  • Methods
  • Properties Similarly, date classes also have some methods that help the developer deal with dates in detail.

Date Methods

  • getFullYear: get the full year
  • getMonth: get the time in a month
  • getDay: get the time in the date
  • getHours: get the time in hours
  • getSeconds: get the time in seconds
  • getMilliseconds: get the time in milliseconds
  • getTime: get the time elapsed since 1 January 1976
    Date class also provide methods to set the date, as follows

  • setFullYear: set the full year

  • setMonth: set the time in a month

  • setDay: set the time in the date

  • setHours: set the time in hours

  • setSeconds: set the time in seconds

  • setMilliseconds: set the time in milliseconds
    The above methods won’t be very useful in development but some applications do need them again it totally depends on the requirements.

getTime method
Get the time elapsed from 1 January 1976, it’s the most used method in javascript when dealing with dates.

I am using this in almost every place where API development or saving data in the database is required. In most places, this method is used since it is easy to use.

This method will give a timestamp of the current time in the form of a large number.

const timestamp = 1677216000000; 
// Timestamp for October 26, 2023, 12:00:00

const specificDate = new Date(timestamp);
This timestamp is used to create the date back using Date constructor
Enter fullscreen mode Exit fullscreen mode

Date Formatting and Parsing

The date constructor gives the date according to the user's local time, so if I am in India, the date constructor calculates everything acc. to GMT + 4 hours or my timezone.

As a developer, you have to take care of different time zones when working with dates in the application.

To format the date into the local timezone we need formatting and javascript to provide a method and class to do the same.

const date = new Date();
const options = { year: 'numeric', month: 'long', day: 'numeric' };
const formattedDate = new Intl.DateTimeFormat('en-US', options).format(date);
console.log(formattedDate); // Output: October 26, 2023
Enter fullscreen mode Exit fullscreen mode

We can also use the javascript date parse method or moment.js library to parse the date according to the timezone.

new Date(Date.parse(date)) // parsing using date method

moment(date).toDate() // parsing using moment.js

Enter fullscreen mode Exit fullscreen mode

Date in Timestamps

This is the most important part for developers, date in timestamps. The reason behind this is that most of the arithmetic operations were done using this timestamp.

  • Timestamp can be easily stored and parsed into date formats
  • Timestamp is a low-size string takes less computer space
  • Timestamp works in all kinds of compilers as it’s just a string
  • Timestamp can be used to perform Maths operations like subtract and add
  • Timestamp can be compared just using operators such as > or <
  • A lot of things can be done simply using timestamps.

Most of the developers prefer timestamp over any other date format.

const date1 = new Date('2023-10-26');
const date2 = new Date('2023-10-27');

if (date1.getTime() === date2.getTime()) {
    console.log('Dates are equal.');
} else if (date1.getTime() < date2.getTime()) {
    console.log('date1 is before date2.');
} else {
    console.log('date1 is after date2.');
}

const timeDifference = Math.abs(date2.getTime() - date1.getTime()); // Difference in milliseconds
const daysDifference = Math.ceil(timeDifference / (1000 * 60 * 60 * 24)); // Convert milliseconds to days
Enter fullscreen mode Exit fullscreen mode

This is the basic code for comparing 2 dates, date1 and date2 by simply converting the actual date into a timestamp using the Date constructor.

const date = new Date("2023-10-26")
// will give timestamp string

Date.now()
// will also return the current timezone timestamp 
Enter fullscreen mode Exit fullscreen mode
const timeDifference = Math.abs(date2.getTime() - date1.getTime()); // Difference in milliseconds
const daysDifference = Math.ceil(timeDifference / (1000 * 60 * 60 * 24)); // Convert milliseconds to days

We can also calculate the time difference in time or milliseconds 
and in days 
Enter fullscreen mode Exit fullscreen mode

Libraries for Dates

There are several libraries in JavaScript that help in handling dates efficiently. Here are a few popular ones:

Conclusion

In this journey through dates in programming, we explored the foundational concepts behind the Date object in JavaScript. From understanding the basics of the Date constructor to mastering various date methods, formatting, and parsing, we've covered a wide array of topics.

Remember, dates are not just numbers; they are gateways to managing time-related data effectively. Libraries like date-fns, Luxon, and Moment.js simplify the complexities, ensuring accurate and dynamic applications.

See you in the next one!

Happy coding,
Shrey
iHateReading

Top comments (0)