Angular 4中如何将ng2-jalali-date-picker值转为Date类型而非字符串?
Hey there! I’ve dealt with this exact issue using ng2-jalali-date-picker before, so let’s break down how to turn that Jalali date string into a valid JavaScript Date object you can store in your database.
The key thing to remember: the picker returns a Jalali (Persian) calendar date string, which can’t be directly passed to new Date() (since that expects Gregorian dates). We need to convert it to Gregorian first, then get the Date type.
Step 1: Add the moment-jalaali Library
The easiest and most reliable way to handle Jalali-Gregorian conversions is with moment-jalaali—it’s a battle-tested library that handles all edge cases (like leap years) correctly. Install it via npm:
npm install moment-jalaali --save
Step 2: Integrate It Into Your Component
In the Angular component where you’re using the date picker, import the library and add the conversion logic:
import { Component } from '@angular/core'; // Import moment-jalaali import * as moment from 'moment-jalaali'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent { // Store the raw string from the picker selectedJalaliDate: string; // This will hold our converted Date object gregorianDate: Date; // Trigger this when the date is selected in the picker onDateSelected(dateString: string) { this.selectedJalaliDate = dateString; // Convert Jalali string to a Gregorian moment object // Make sure the format matches your picker's output! // Common formats are 'jYYYY/jMM/jDD' or 'jDD-jMM-jYYYY' const convertedMoment = moment(dateString, 'jYYYY/jMM/jDD'); // Convert the moment object to a native JavaScript Date this.gregorianDate = convertedMoment.toDate(); // Now you can send this.gregorianDate to your database console.log('Converted Date:', this.gregorianDate); // Verify it works! } }
Step 3: Match the Date Format
Double-check that the format string you pass to moment() matches exactly what your ng2-jalali-date-picker outputs. For example, if your picker returns dates like 1402/05/10, use 'jYYYY/jMM/jDD'. If it’s 10-05-1402, use 'jDD-jMM-jYYYY'.
Alternative: No External Libraries (Not Recommended)
If you really don’t want to add a dependency, you could write your own Jalali-to-Gregorian conversion function. But this is risky—Jalali calendar rules are non-trivial, and you’ll likely run into bugs with leap years or edge dates. Stick with moment-jalaali unless you have a strict constraint against adding libraries.
内容的提问来源于stack exchange,提问作者fariba.j

