
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Getting century from year in JavaScript
We are required to write a JavaScript function that takes in a number or a string that represents a year. From that year our function should figure out and return the century that the year falls in.
For example −
f("2000") = 20 f(1999) = 20 f("2002") = 21
Following is the code −
Example
const centuryFromYear = year => { if(typeof year == 'string'){ if(year.toString().slice(-2) == '00'){ return year.toString().slice(0,2); }else{ return (Math.floor(+year/100) +1).toString(); }; }else if(typeof year == 'number'){ return Math.floor((year-1)/100) + 1; }else{ return undefined; }; }; console.log(centuryFromYear("2000")); console.log(centuryFromYear("2002")); console.log(centuryFromYear(1999));
Output
Following is the output on console −
20 21 20
- Related Articles
- Get the correct century from 2-digit year date value - JavaScript?
- Input year and find in which century it falls without using slice() in JavaScript
- Program to find century for a year in C++
- Display first two digits of year in Java (two-digit century)
- Getting day of the year from DD/MM/YYYY using function in SAP system
- Python Pandas - Format the Period object and display the Year without century
- Getting values from HTML5 Canvas to JavaScript
- Finding day of week from date (day, month, year) in JavaScript
- What is the probability of getting $53$ Mondays in a leap year?
- Getting equal or greater than number from the list of numbers in JavaScript
- How to print current year in JavaScript?
- JavaScript – Getting Coordinates of mouse
- JavaScript program to check if a given year is leap year
- How to get the current year in JavaScript?
- Sort array by month-year JavaScript

Advertisements