【问题标题】:How to assign UtcNow to a DateTime picker value property?如何将 UtcNow 分配给 DateTime 选择器值属性?
【发布时间】:2016-07-13 13:34:08
【问题描述】:

我正在使用 Bootstrap 3 日期时间选择器 from here. 在加载 Razr 表单时,我想将默认时间设置为当前的 UtcNow 时间戳。

为了设置这个默认值,我尝试了多种不同的 DateTime 格式。但是控件似乎不接受传入的格式。

尝试了一些格式:

//Format #1
DateTime.UtcNow.ToString("yyyyMMddHHmmtt");

//Format #2
string.Format("{0:g}", DateTime.UtcNow);

我知道 DateTime 选择器在选择时间时使用的格式如下,07/13/2016 2:43 AM,所以我想如果我可以将 UTC 时间转换为这种格式,它将接受时间戳。

我验证我可以将此值分配给具有相同 Razr 语法的常规输入元素,从而排除了值未传递的问题。

问题:

如何将 UtcNow 分配给 DateTime 选择器默认值属性?

控制器:在控制器中,我将string.Format("{0:g}", DateTime.UtcNow); 作为模型属性传入。

//Create a dynamic object to store list of different model types.
dynamic dynamicEscalationModel = new ExpandoObject();
dynamicEscalationModel.OutageStartTime = string.Format("{0:g}", DateTime.UtcNow);

查看:然后我使用@ 符号将此值分配给日期时间选择器:

<!-- Outage Start -->
<div class="form-group">
    <label class="col-md-9 control-label" style="text-align: left;" for="OutageStartDisplay">Outage Start (*UTC)</label>
    <div class="col-md-9">
        <div class='input-group date' id='OutageStartDisplay'>
            <input type='text' class="form-control" id="OutageStartDisplayInput" name="OutageStartDisplayInput" value="@Model.OutageStartTime" />
            <span class="input-group-addon" id="OutageStartDisplayCalendar">
                <span class="glyphicon glyphicon-calendar"></span>
            </span>
        </div>
    </div>
</div>

为了测试,我添加了第二个普通输入并且模型属性被正确绑定:

<input type='text' class="form-control" id="" name="" value="@Model.OutageStartTime" />

我的脚本标签中的 DateTimepicker 初始化:

//Init the Outage Start date time picker
$(function () {
    $('#OutageStartDisplay').datetimepicker({
    });
});

【问题讨论】:

    标签: c# razor model-view-controller twitter-bootstrap-3 datetimepicker


    【解决方案1】:

    既然你现在得到了UTC,为什么不直接从客户端做呢:

        <script type="text/javascript">
            $(function () {
                var t = new Date(); 
                t.setMinutes(t.getMinutes() + t.getTimezoneOffset());
    
                $('#OutageStartDisplay').datetimepicker({
                    defaultDate: t,
                });
            });
        </script>
    

    【讨论】:

    • 我已经尝试过 new Date().getTime() ,它给了我本地时区而不是 UTC。还有其他想法吗?
    【解决方案2】:

    将此添加到脚本标签您需要在那里初始化它:

          $('#OutageStartDisplay').datetimepicker({
            format: 'm/d/Y H:i:s',
            theme: 'dark',
            startDate: '@Model.OutageStartTime'
        });
    

    【讨论】:

    • 添加格式和 startDate 会破坏选择器,因为它无法从中选择,但 DateTime 已设置。控制台错误为:“bootstrap-datetimepicker.min.js:8 Uncaught TypeError: option startDate is not recognize”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多