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
Selected Reading
Get the correct century from 2-digit year date value - JavaScript?
When working with 2-digit year values, you need to determine which century they belong to. A common approach is using a pivot year to decide between 19XX and 20XX centuries.
Example
Following is the code −
const yearRangeValue = 18;
const getCorrectCentury = dateValues => {
var [date, month, year] = dateValues.split("-");
var originalYear = +year > yearRangeValue ? "19" + year : "20" + year;
return new Date(originalYear + "-" + month + "-" + date).toLocaleDateString('en-GB')
};
console.log(getCorrectCentury('10-JAN-19'));
console.log(getCorrectCentury('10-JAN-17'));
console.log(getCorrectCentury('10-JAN-25'));
Output
10/01/2019 10/01/2017 10/01/2025
How It Works
The pivot year (18 in this example) determines the century assignment:
- Years > 18 (19, 20, 21, etc.) are treated as 19XX (1919, 1920, 1921)
- Years ? 18 (00-18) are treated as 20XX (2000-2018)
Alternative Approach with Current Year
const getCorrectCenturyDynamic = (dateString) => {
var [date, month, year] = dateString.split("-");
var currentYear = new Date().getFullYear() % 100; // Get 2-digit current year
var fullYear = +year > currentYear ? "19" + year : "20" + year;
return new Date(fullYear + "-" + month + "-" + date).toLocaleDateString('en-GB');
};
console.log(getCorrectCenturyDynamic('10-JAN-19'));
console.log(getCorrectCenturyDynamic('10-JAN-50'));
Output
10/01/2019 10/01/1950
Conclusion
Use a pivot year strategy to convert 2-digit years to 4-digit years. Choose your pivot based on your data's expected range for accurate century determination.
Advertisements
