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

如何在AngularJS中设置Mobiscroll日期选择器输出1960-04-30 00:00:00.000格式

实现Mobiscroll日历选择器输出指定日期格式(AngularJS)

我来帮你搞定这个需求!要让Mobiscroll日历选择器选中日期后输出1960-04-30 00:00:00.000这种格式,我们可以从Mobiscroll配置和AngularJS日期处理两方面入手,具体步骤如下:

1. 配置Mobiscroll的回调与返回格式

首先在你的Mobiscroll设置(settings对象)里,指定选中日期后的回调逻辑,同时确保选择器返回原生Date对象(方便后续格式转换):

$scope.settings = {
    // 可选:设置选择器界面显示的日期格式,比如yyyy-mm-dd
    display: 'yyyy-mm-dd',
    // 关键:让选择器返回原生Date对象,而非字符串
    returnFormat: 'date',
    // 选中日期后的回调函数,在这里处理格式转换
    onSet: function(event, inst) {
        if (event.value) {
            // 调用自定义格式转换函数处理日期
            $scope.mycalendar = formatDateToRequired(event.value);
            // 手动触发AngularJS脏检查,确保视图同步更新
            $scope.$apply();
        }
    }
};

2. 编写日期格式转换函数

写一个工具函数,把原生Date对象转换成你需要的yyyy-mm-dd hh:mm:ss.sss格式:

function formatDateToRequired(date) {
    // 提取年份
    const year = date.getFullYear();
    // 提取月份(注意月份是0起始,需+1后补零到两位)
    const month = String(date.getMonth() + 1).padStart(2, '0');
    // 提取日期并补零到两位
    const day = String(date.getDate()).padStart(2, '0');
    // 固定时分秒为00:00:00.000
    const timeSegment = '00:00:00.000';

    // 拼接成最终格式字符串
    return `${year}-${month}-${day} ${timeSegment}`;
}

3. 集成到AngularJS控制器

把上述代码整合到你的AngularJS控制器中,完整示例如下:

angular.module('yourAppModule', [])
.controller('YourCalendarController', function($scope) {
    // 初始化Mobiscroll配置
    $scope.settings = {
        display: 'yyyy-mm-dd',
        returnFormat: 'date',
        onSet: function(event, inst) {
            if (event.value) {
                $scope.mycalendar = formatDateToRequired(event.value);
                $scope.$apply();
            }
        }
    };

    // 自定义日期格式转换函数
    function formatDateToRequired(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const timeSegment = '00:00:00.000';
        return `${year}-${month}-${day} ${timeSegment}`;
    }

    // 初始化日期变量
    $scope.mycalendar = '';
});

4. 替代方案:用$watch监听日期变化

如果你不想用onSet回调,也可以通过AngularJS的$watch监听mycalendar的变化,自动转换格式:

$scope.$watch('mycalendar', function(newDate) {
    if (newDate instanceof Date) {
        $scope.mycalendar = formatDateToRequired(newDate);
    }
});

这种方式不需要手动调用$apply(),AngularJS会自动处理视图更新。

这样配置后,用户选中日期时,$scope.mycalendar就会自动变成你需要的1960-04-30 00:00:00.000格式啦!

内容的提问来源于stack exchange,提问作者Avinash Bailore

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:06:43