如何将波斯数字转英文数字及波斯历当前日期转数字用于计算
First, let’s tackle the core problem: when you fetch a Persian date with toLocaleDateString('fa-IR'), it returns Persian digits (۰۱۲۳۴۵۶۷۸۹) which can’t be directly used for numerical calculations. We need a reliable way to convert these to standard English numerals (0123456789).
Step 1: Build a Reusable Digit Conversion Helper
This function will convert any Persian digits in a string to English ones by leveraging their consecutive Unicode values—no messy per-digit regex replacements needed:
function convertPersianDigitsToEnglish(inputString) { // Target all Persian digit characters (Unicode range U+06F0 to U+06F9) return inputString.replace(/[\u06F0-\u06F9]/g, persianChar => { // Adjust Unicode value to map to the corresponding English digit return String.fromCharCode(persianChar.charCodeAt(0) - 1728); }); }
Step 2: Update Your HTMLUI Prototype
Let’s modify your existing displayYear method to retrieve the Persian year, convert it to English digits, and extend it to handle full date and current time conversion as needed:
function HTMLUI() {} HTMLUI.prototype.displayYear = function() { // Get full Persian date string const persianDate = new Date().toLocaleDateString('fa-IR'); // Extract and convert the year to English digits (ready for calculations) const persianYear = persianDate.slice(0, 4); const englishYear = convertPersianDigitsToEnglish(persianYear); console.log('Converted Shamsi Year (English digits):', englishYear); // Optional: Convert and log the full Persian date const englishFullDate = convertPersianDigitsToEnglish(persianDate); console.log('Full Converted Shamsi Date:', englishFullDate); }; // Add a method to handle current time conversion in Persian locale HTMLUI.prototype.displayCurrentTime = function() { const persianTime = new Date().toLocaleTimeString('fa-IR'); const englishTime = convertPersianDigitsToEnglish(persianTime); console.log('Converted Current Time (English digits):', englishTime); };
How It Works
- The regex
/[\u06F0-\u06F9]/gmatches every Persian digit in the input string. - Subtracting 1728 from the Unicode value of each Persian digit maps it directly to the corresponding English digit (e.g., ۰ → 0, ۱ → 1).
- Converted strings can be parsed to numbers with
parseInt()orparseFloat()for calculations.
Example Usage
const ui = new HTMLUI(); ui.displayYear(); // Sample output: // Converted Shamsi Year (English digits): 1402 // Full Converted Shamsi Date: 1402/09/15 ui.displayCurrentTime(); // Sample output: // Converted Current Time (English digits): 14:30:45
This approach ensures all Persian digits in your date/time strings are converted to usable English numerals for any arithmetic or numerical processing needs.
内容的提问来源于stack exchange,提问作者Mohammad Amiri

