AngularJS指令中Bootstrap datetimepicker选择日期时保留原有时间的问题
I’ve run into this exact frustrating issue before with the Bootstrap datetimepicker in AngularJS directives—when you pick a new date without touching the time picker, the original time (like 00:00) gets wiped out and replaced with the current time. Here’s how I fixed it:
The Root Cause
By default, when you only select a date (no time adjustments), the datetimepicker replaces the time portion of the selected date with the current system time. We need to intercept this change and manually retain the original time values.
Step-by-Step Solution
In your AngularJS directive’s link function, listen for the dp.change event emitted by the datetimepicker. When the event fires:
- Grab the original time (hours, minutes, seconds) from the previous model value
- Apply those time values to the newly selected date
- Update the model with this combined date-time value
Code Example
Here’s how to implement this in your directive:
angular.module('yourApp').directive('datetimePicker', function() { return { require: 'ngModel', link: function(scope, element, attrs, ngModel) { // Initialize datetimepicker with your desired format element.datetimepicker({ format: 'YYYY-MM-DD HH:mm', // Adjust to match your use case // Add other configuration options here }); // Store initial time values when the model is first populated let savedTime; ngModel.$render = function() { if (ngModel.$viewValue) { const initialDate = new Date(ngModel.$viewValue); savedTime = { hours: initialDate.getHours(), minutes: initialDate.getMinutes(), seconds: initialDate.getSeconds() }; } }; // Handle date change event element.on('dp.change', function(e) { if (e.date && savedTime) { // Create a new date with selected date + saved time const updatedDateTime = new Date(e.date); updatedDateTime.setHours(savedTime.hours); updatedDateTime.setMinutes(savedTime.minutes); updatedDateTime.setSeconds(savedTime.seconds); // Sync the updated value with Angular's model scope.$apply(function() { ngModel.$setViewValue(updatedDateTime); // Update savedTime for future date selections savedTime = { hours: updatedDateTime.getHours(), minutes: updatedDateTime.getMinutes(), seconds: updatedDateTime.getSeconds() }; }); } }); } }; });
Key Notes
ngModel.$rendercaptures the initial time values when the model is first set (e.g., your 00:00 initial value).- On
dp.change, we overwrite the new date’s time with the saved values—if the user later adjusts the time, that new time will be preserved for future date picks. scope.$apply()ensures Angular recognizes the model change and updates the view accordingly.
This approach keeps the original time intact when only selecting a new date, while still allowing users to modify the time normally if they want to.
内容的提问来源于stack exchange,提问作者Naomi

