【问题标题】:taking the difference between two bootstrap date picker dates with different formats采用不同格式的两个引导日期选择器日期之间的差异
【发布时间】:2015-01-05 06:33:44
【问题描述】:

我在 Web 应用程序的前端使用 bootstrap datepicker。数据库需要dd-mm-yyyy 格式的所有日期。所以这就是我使用datepicker的方式。

  <script>
            $(function() {
                $(".dates").datepicker({ 
                     format: 'dd-mm-yyyy',
                     autoclose: true
                });
            });
  </script>

我现在有一个新要求来检查两个日期值之间的月差。 我试过这段代码:

var onBookingDate = new Date(jQuery('#datepick_onBooking').val());
var commencingDate = new Date(jQuery('#commencingDate').val());

var msPerMonth = 1000*60*60*24*30;

    alert(onBookingDate );
    alert(commencingDate );
    alert (Math.floor(commencingDate .getTime() - onBookingDate.getTime())/msPerMonth );

在此,它以 mm-dd-yyyy 的格式提醒日期

即:如果我选择 10-02-2015(2015 年 2 月 10 日),它会提醒日期为 2015 年 10 月 2 日。

如何将收到警报的日期格式更改为 dd-mm-yyyy ?我无法将格式更改为 mm-dd-yyyy,因为数据库需要 dd-mm-yyyy 格式的日期。

谢谢!

【问题讨论】:

    标签: jquery twitter-bootstrap datepicker bootstrap-datepicker


    【解决方案1】:

    您正在尝试从 Date 构造函数的无效字符串格式创建日期对象。

    在日期选择器的 API 中使用 getDate() 方法通常比必须使用字符串值并再次转换它们更容易。

    API 通常会返回一个日期对象(jQueryUI、Bootstrap 等)。

    var onBookingDate = jQuery('#datepick_onBooking').datepicker('getDate');
    var commencingDate = jQuery('#commencingDate').datepicker('getDate');
    

    参考:bootstrap datepicker getDate() docs

    【讨论】:

      【解决方案2】:

      每当谈到 javascript 中的日期处理时,现在的首选应该是在您的项目中包含 moment.js。然后,您可以简单地更改日期的格式与

      moment(date here).format('desired format')
      

      查看文档here

      要插入数据库,这就足够了:

      moment(date here).format();   
      

      moment.js 使添加或子日期变得非常容易,您可以使用this plugin to moment.js 轻松处理日期范围

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多