You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 (like MM/DD/YYYY or YYYY-MM-DD), adjust the order of components when creating the Date object.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:06:55