Ionic中ion-datetime绑定Unix时间戳毫秒值的实现疑问
You’re spot-on with your intuition—ditching two-way binding and handling date conversion manually is exactly the way to go here. The ion-datetime component natively works with Date objects or ISO strings, but since your model requires a numeric Unix timestamp (milliseconds), we’ll split the binding into two separate parts: one-way for displaying the date, and an event handler to update the model with the converted value.
Step 1: Adjust the Template (.html)
Replace the two-way [(ngModel)] with a one-way [ngModel] to pass the formatted date to the picker, and keep the ngModelChange event to handle user selections:
<ion-datetime displayFormat="MMM DD, YYYY" pickerFormat="MMM DD, YYYY" [ngModel]="getDisplayDate(person.date_of_birth)" (ngModelChange)="changeModel($event)" ></ion-datetime>
Step 2: Update the Component (.ts)
First, fix your person type definition (use number instead of numeric for TypeScript compatibility):
interface Person { name: string; date_of_birth: number; // Stores Unix timestamp in milliseconds } // Initialize with default values (adjust based on your needs) let person: Person = { name: '', date_of_birth: 0 };
Then add two helper functions to handle the conversion in both directions:
getDisplayDate: Converts the stored timestamp back to a Date object so the picker can show a human-readable date.changeModel: Takes the selected Date from the picker and converts it to a Unix timestamp (milliseconds) to store in your model.
// Convert stored timestamp to Date for picker display getDisplayDate(timestamp: number): Date | null { return timestamp ? new Date(timestamp) : null; } // Convert selected Date to timestamp and update the model changeModel(selectedDate: Date) { if (selectedDate) { person.date_of_birth = selectedDate.getTime(); // Gets milliseconds since epoch } else { person.date_of_birth = 0; // Or handle empty selection as needed (e.g., set to null) } }
Key Details to Keep in Mind
- This setup ensures
person.date_of_birthstays a numeric timestamp everywhere else (database storage, REST API sync)—perfect for your use case. - The
getDisplayDatefunction makes sure existing data loaded from PouchDB/SQLite will display correctly in the picker. - If your schema allows null values for the date, adjust the null checks to set
person.date_of_birthtonullinstead of0.
This approach gives you full control over the data format without relying on pipes in action expressions (which aren’t supported in Angular event handlers anyway).
内容的提问来源于stack exchange,提问作者stephen

