Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Getting century from year in JavaScript
In JavaScript, determining the century from a given year is a common programming task. A century represents a period of 100 years, where the 1st century includes years 1-100, the 20th century covers 1901-2000, and so on.
Understanding Century Calculation
The key insight is that centuries don't align perfectly with hundreds. For example:
- Year 1900 belongs to the 19th century (not 20th)
- Year 2000 belongs to the 20th century (not 21st)
- Year 2001 begins the 21st century
Logic and Algorithm
To find the century from a year:
- Divide the year by 100
- Round up to the nearest integer using
Math.ceil() - Return the result
The Math.ceil() function automatically handles the rounding logic, ensuring years ending in 01-99 round up correctly.
Implementation
function getCentury(year) {
return Math.ceil(year / 100);
}
// Test with various years
console.log("Year 1: Century", getCentury(1));
console.log("Year 100: Century", getCentury(100));
console.log("Year 101: Century", getCentury(101));
console.log("Year 1900: Century", getCentury(1900));
console.log("Year 2000: Century", getCentury(2000));
console.log("Year 2023: Century", getCentury(2023));
Year 1: Century 1 Year 100: Century 1 Year 101: Century 2 Year 1900: Century 19 Year 2000: Century 20 Year 2023: Century 21
Alternative Approach
You can also use manual calculation with conditional logic:
function getCenturyManual(year) {
let century = Math.floor(year / 100);
if (year % 100 !== 0) {
century += 1;
}
return century;
}
// Test the alternative approach
console.log("Manual calculation for 1999:", getCenturyManual(1999));
console.log("Manual calculation for 2000:", getCenturyManual(2000));
Manual calculation for 1999: 20 Manual calculation for 2000: 20
Comparison
| Method | Code Complexity | Readability | Performance |
|---|---|---|---|
Math.ceil(year / 100) |
Simple | High | O(1) |
| Manual calculation | Moderate | Medium | O(1) |
Practical Example
// Function to get century with descriptive output
function describeCentury(year) {
const century = Math.ceil(year / 100);
const suffix = century === 1 ? 'st' : century === 2 ? 'nd' : century === 3 ? 'rd' : 'th';
return `Year ${year} belongs to the ${century}${suffix} century`;
}
console.log(describeCentury(1776));
console.log(describeCentury(2024));
Year 1776 belongs to the 18th century Year 2024 belongs to the 21st century
Conclusion
Using Math.ceil(year / 100) provides the simplest and most reliable way to calculate centuries from years in JavaScript. This approach automatically handles edge cases and maintains O(1) time complexity for efficient computation.
