JavaScript Date prototype Property
Lakmal Asela
Posted on July 29, 2024
The Date.prototype object in JavaScript is used to extend or override the behavior of Date instances. This provides a means of adding custom methods and properties to all Date objects.
Extending Date with Custom Methods
You can add custom methods to Date.prototype to make them available on all instances of Date. For example, you may want to add a method that returns the number of total days.
Date.prototype.daysFromStartOfYear = function() {
const startOfYear = new Date(this.getFullYear(), 0, 1); // January 1st of the current year
const oneDay = 24 * 60 * 60 * 1000; // Milliseconds in one day
const differenceInTime = this.getTime() - startOfYear.getTime();
return Math.floor(differenceInTime / oneDay) + 1; // Add 1 to include the start day
}
Explanation
Date.prototype.daysFromStartOfYear
: Defines a new method daysFromStartOfYear on the Date prototype, making it available to all Date instances.new Date(this.getFullYear(), 0, 1)
: Creates a Date object for January 1st of the current year (this.getFullYear()).this.getTime() - startOfYear.getTime()
: Calculates the difference in milliseconds between the current date (this) and January 1st of the year.Math.floor(differenceInTime / oneDay) + 1
: Converts milliseconds to days. Adding 1 ensures that January 1st is counted as day 1.
This solution won't modify the Date.prototype object, and in some cases, may be useful when you need to apply the method and not affect all instances of Date
Posted on July 29, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.