JavaScript中如何逆向转换Date.toLocaleString生成的本地化字符串?
Solution to Convert Locale String Back to Date Object
Absolutely, you can do this without external libraries—you just need to manually parse the specific format of your locale string since the built-in Date methods don’t handle inconsistent locale formats well.
Here’s why your initial attempts failed: new Date(x) and Date.parse(x) rely on standardized date formats (like ISO 8601), but locale strings vary widely based on browser and region settings. Your example string "20.05.2018, 10:21:37" uses a DD.MM.YYYY, HH:mm:ss format, which isn’t recognized by the default parsers.
Step-by-Step Implementation:
You can break down the string into its components and build a new Date object manually:
function localeStringToDate(localeStr) { // Split date and time sections const [datePart, timePart] = localeStr.split(', '); // Extract day, month, year from the date segment const [day, month, year] = datePart.split('.').map(Number); // Extract hours, minutes, seconds from the time segment const [hours, minutes, seconds] = timePart.split(':').map(Number); // Create Date object (note: JavaScript months are 0-indexed) return new Date(year, month - 1, day, hours, minutes, seconds); } // Test with your example const x = "20.05.2018, 10:21:37"; const dateObj = localeStringToDate(x); console.log(dateObj); // Outputs: Mon May 20 2018 10:21:37 GMT+... (matches your local timezone) console.log(dateObj.toLocaleString()); // Should match your original input string
Key Notes:
- This function is tailored to your specific locale format (
DD.MM.YYYY, HH:mm:ss). If your locale uses a different structure (likeMM/DD/YYYYorYYYY-MM-DD), adjust the order of components when creating theDateobject. - For robustness, you could add input validation checks (e.g., ensuring the string splits into the correct number of parts, verifying numeric values are valid) to avoid unexpected errors.
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

