如何将moment.js时间选择器输出格式转为hh:mm:ss适配Django TimeField
The issue here is that the mdc-datetime-picker binds a JavaScript Date object to your ng-model, which gets serialized to an ISO 8601 string (like 2018-01-23T12:38:07.439Z) when sent to your Django backend. Django's TimeField expects a plain time string in HH:mm:ss format, so we need to convert the Date object to the correct format before sending the data.
Here are two straightforward approaches to fix this:
Approach 1: Format the Time in Your Save Function
You can use moment.js (which you're already using with the picker) to convert the Date object to the required string format directly in your saveChange method.
Update your AngularJS controller code:
vm.saveChange = function() { // Convert the Date object to HH:mm:ss format if (data.openingTime) { data.openingTime = moment(data.openingTime).format('HH:mm:ss'); } // Proceed with sending your REST API request here // Example: $http.post('/api/shop/', data); };
Note: This works because the picker will still recognize the Date object in ng-model for display (keeping your hh:mm a format), but we overwrite it with the backend-compatible string just before saving.
Approach 2: Use a Temporary Model for the Picker
If you want to avoid modifying the original data.openingTime until you're ready to save, use a temporary variable to bind the picker, then format it on change or save.
Step 1: Update Your Template
Modify the input to bind to a temporary variable instead of data.openingTime:
<md-input-container flex-gt-sm class="md-block"> <label>Opening Time</label> <md-icon md-svg-src="/cityaplfreelisting/media/time.svg" class="mdicon"></md-icon> <input required mdc-datetime-picker date="false" time="true" type="text" short-time="true" show-todays-date click-outside-to-close="true" auto-ok="true" min-date="minDate" minute-steps="1" format="hh:mm a" ng-change="vm.formatOpeningTime()" ng-model="vm.tempOpeningTime"> </md-input-container>
Step 2: Add Logic to Your Controller
Add the temporary variable and formatting function:
// Initialize temporary variable vm.tempOpeningTime = null; // Format the time when the picker value changes vm.formatOpeningTime = function() { if (vm.tempOpeningTime) { data.openingTime = moment(vm.tempOpeningTime).format('HH:mm:ss'); } }; vm.saveChange = function() { // Now data.openingTime is in the correct format for Django // Send your API request here };
Why This Works
moment(data.openingTime)parses the JavaScript Date object into a moment instance..format('HH:mm:ss')converts that moment to a string in the exact format Django'sTimeFieldexpects (usehh:mm:ssinstead if you need 12-hour format—Django accepts either as long as it's a valid time string).
Just ensure moment.js is properly included in your AngularJS app so these methods work as expected.
内容的提问来源于stack exchange,提问作者Divakar Yadav

