You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS指令中Bootstrap datetimepicker选择日期时保留原有时间的问题

Fix: Preserve Original Time When Selecting Date in 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.$render captures 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:10:57