从datepicker获取日期并在groovy中解析它时无法保存对象

时间:2016-05-31 09:59:31

标签: grails groovy datepicker

我是grails上的新手。我在GSP页面中使用了datepicker。当我使用它来获取日期并在服务器端解析它时,无法保存该对象。

我的网域

class PurchaseOrder {
    Date orderDate;
    Date deliveryDate;
    Double totalQuantity;
    Double deliveredQuantity;
    Double totalCost;
    Long totalItem;
    Long deliveredTotalItem;
    Long requisition

    static belongsTo = [branch:OrganizationalBranch,orderedBy: Employee, supplier: Supplier]
    static hasMany = [itemDetails:OrderDetails]



    static constraints = {
        deliveryDate(nullable: true);
        deliveredQuantity(nullable: true);
        deliveredTotalItem(nullable: true);

        itemDetails(nullable: true);
        orderDate(nullable: true);
        totalItem(nullable: true);
        totalQuantity(nullable: true);
        totalCost(nullable: true);
    }
}

我的GSP是:

<div class="fieldcontain ${hasErrors(bean: purchaseOrderInstance, field: 'deliveryDate', 'error')} ">
    <label for="deliveryDate">
        <g:message code="purchaseOrder.deliveryDate.label" default="Delivery Date" />

    </label>
    <g:field type="deliveryDate" id="deliveryDate" name="deliveryDate" class="datepicker" />

</div>

Controller的代码是:

try {
            String orderDateSt = params?.deliveryDate
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy")
            def orderDate = new Date().parse("MM/dd/yyyy", orderDateSt.trim())           
            purchaseOrderInstance.deliveryDate = orderDate
        }catch (Exception ex) {
            ex.getMessage()
            ex.printStackTrace()
        }

错误是:

purchase.PurchaseOrderController  - Field error in object 'com.sb.ims.purchase.PurchaseOrder' on field 'deliveryDate': rejected value [06/30/2016]; codes [com.sb.ims.purchase.PurchaseOrder.deliveryDate.typeMismatch.error,com.sb.ims.purchase.PurchaseOrder.deliveryDate.typeMismatch,purchaseOrder.deliveryDate.typeMismatch.error,purchaseOrder.deliveryDate.typeMismatch,typeMismatch.com.sb.ims.purchase.PurchaseOrder.deliveryDate,typeMismatch.deliveryDate,typeMismatch.java.util.Date,typeMismatch]; arguments [deliveryDate]; default message [Unparseable date: "06/30/2016"]

我该如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

如果你的Grails版本是&gt; = 2.3,你应该可以使用BindingFormat注释而不是解析控制器中的日期:

import org.grails.databinding.BindingFormat

class PurchaseOrder { 
    @BindingFormat('MM/dd/yyyy') 
    Date orderDate
    @BindingFormat('MM/dd/yyyy')
    Date deliveryDate
    ....
}