引导日期时间选择器显示格式与值格式 [英] Bootstrap date time picker display format vs value format

查看:120
本文介绍了引导日期时间选择器显示格式与值格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下插件来选择日期和时间。

I am using the following plugin for selecting date and time.

https://eonasdan.github.io/bootstrap-datetimepicker/

在大多数情况下,它的效果很好。但是在某些情况下,我在输入字段中显示日期为MM / DD / YYYY但是当我提交给服务器时,我需要它作为YYYY-MM-DD

It works great in most cases. However in some cases I display the date in the input field as MM/DD/YYYY but when I submit to server, I need it as YYYY-MM-DD

什么是实现这一目标的最佳方法吗?我正在考虑覆盖表单的提交功能。但我有点想避免这种情况,因为我想以某种方式使用他们的事件来完成它所以我可以在一个地方包含代码,而不是为每个表单添加一堆逻辑。

What is the best way to accomplish this? I am thinking of overriding submit function for the form. But I kind of want to avoid this as I would like to somehow do it all using their events so I can contain the code in one place instead of adding a bunch of logic for each form.

推荐答案

Ashish和Chris代码可能有效,但是因为 Bootstrap 3 Datepicker需要Moment.js ,为什么不使用片刻.js Parse (用于解析为datepicker选择的自定义或区域设置格式的日期)和 Moment.js格式(以ISO格式转换日期,例如发送给ASP.NET控制器或接受DateTime格式的其他端点)?

Ashish and Chris code may work, but since Bootstrap 3 Datepicker requires Moment.js, why not use Moment.js Parse (to parse the date from your custom or locale format chosen for the datepicker) and Moment.js Format (to convert the date in ISO format e.g. to be sent to an ASP.NET controller or other endpoints accepting that kind of format for DateTime)?

因此代码会更短,如下所示:

So the code would be way much shorter, like this:

  $('#datetimepicker1').on("dp.change",
    function (e) {
      var submitDateString = '';
      if (e.Date) {
        submitDateString = e.Date.format();
      }
      $("#datetime-submit").val(submitDateString);
    });

注意(见下面的评论): e.Date 可能需要 e.date 才能工作。

Note (see comment below): e.Date may need to be e.date to work.

说明:


  • dp.change事件(e)有一个Date属性,它是一个时刻对象,所以你甚至不需要关心你选择的日期格式是什么日期选择器。

  • 当清除日期选择器时e.Date为false,因此if检查。

  • $(#datepicker1)是输入字段,我绑定bootstrap
    datepicker。

  • $(#datetime-submit)是我的隐藏输入字段。

  • the dp.change event (e) has a Date property, which is a moment object, so you don't even need to care what was the date format you chose for the datepicker.
  • when the datepicker is cleared e.Date is false, thus the if check.
  • $("#datepicker1") is the input field where I bind bootstrap datepicker.
  • $("#datetime-submit") is my hidden input field.

要回答OP,如果要提交的格式为YYYY-MM-DD,请使用:

To answer the OP, if the desired format to submit is "YYYY-MM-DD", then use:

submitDateString = e.Date.format("YYYY-MM-DD");

我刚发现 Moment.js 并喜欢它。用它来进行日期解析和显示更容易。

I just discovered Moment.js and love it. Use it to make date parsing & displaying easier.

这篇关于引导日期时间选择器显示格式与值格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆