如何判断经new Date解析后的日期字符串的精度?
new Date() Great question—this is a common gotcha with JavaScript's Date constructor! The problem is that new Date() automatically fills in missing date components with default values (like January 1st, 00:00:00), so you can’t rely solely on the parsed Date object’s values to judge precision (e.g., a month of January doesn’t always mean the input was year-only, since the actual date might genuinely be in January).
Here’s how to solve this properly:
Core Idea: Use the Original Input String
The parsed Date object discards information about which components were explicitly provided vs. auto-filled. So your first rule is: always keep hold of the original date string you passed to new Date(). Precision can only be determined by analyzing this raw input.
Step-by-Step Precision Detection
Use pattern matching (regular expressions) to identify which date components are present in the original string. Below are common cases and how to handle them:
1. Year-Only Precision
The input string contains nothing but a year (2 or 4 digits):
- Matches patterns like
^\d{2,4}$(e.g.,'2017','17') - Example: Even though
new Date('2017')returnsSun Jan 01 2017 00:00:00, the original string tells us it’s only year-precise.
2. Month-Level Precision
The input includes both a year and a month (in any common format):
- Matches patterns like
^\d{4}-\d{2}$(e.g.,'2017-10'),^\w{3,} \d{4}$(e.g.,'oct 2017'), or'\d{2}/\d{4}'(e.g.,'10/2017') - Example:
new Date('oct 2017')returnsSun Oct 01 2017 00:00:00, but the original string confirms we only have month-level precision.
3. Day-Level Precision
The input includes year, month, and day (in any common format):
- Matches patterns like
^\d{4}\.\d{1,2}\.\d{1,2}$(e.g.,'2017.3.15'),^\d{1,2} \d{1,2} \d{2,4}$(e.g.,'3 15 17'), or'\w{3,} \d{1,2}, \d{4}'(e.g.,'Mar 15, 2017') - Example:
new Date('3 15 17')returnsWed Mar 15 2017 00:00:00, and the original string confirms full day precision.
Example JavaScript Implementation
Here’s a practical function to put this logic to use:
function getDatePrecision(dateString) { const trimmed = dateString.trim(); // Check for day-level precision (year + month + day present) const dayRegex = /(\d{4}[-./]\d{1,2}[-./]\d{1,2})|(\d{1,2}[-./ ]\d{1,2}[-./ ]\d{2,4})|(\w{3,} \d{1,2},? \d{4})/i; if (dayRegex.test(trimmed)) { return "day"; } // Check for month-level precision (year + month present) const monthRegex = /(\d{4}[-./]\d{1,2})|(\w{3,}[-./ ]\d{4})|(\d{1,2}[-./ ]\d{4})/i; if (monthRegex.test(trimmed)) { return "month"; } // Check for year-only precision const yearRegex = /^\d{2,4}$/; if (yearRegex.test(trimmed)) { return "year"; } // Fallback for unrecognized formats return "unknown"; } // Test the function console.log(getDatePrecision("2017")); // "year" console.log(getDatePrecision("2017-10")); // "month" console.log(getDatePrecision("oct 2017")); // "month" console.log(getDatePrecision("2017.3.15")); // "day" console.log(getDatePrecision("3 15 17")); // "day"
Key Notes
- Adjust the regex patterns to cover locale-specific date formats (e.g.,
'15/03/2017'for day/month/year). - Always validate the input is a valid date first (using
!isNaN(new Date(dateString).valueOf())) before checking precision. - Never trust the parsed
Dateobject’s default values to infer precision—always go back to the original string.
内容的提问来源于stack exchange,提问作者LarsW

