聚合物 - Vaadin日期选择器; Vaadin Grid:如何更改日期格式?

时间:2017-09-12 01:04:56

标签: javascript date polymer vaadin vaadin-grid

有人知道如何更改vaadin-date-picker的日期格式吗? 我正在使用聚合物和vaadin-grid,无法更改日期格式。

vaadin-date-picker.html元素的代码是:

<!--
@license
Copyright (c) 2017 Vaadin Ltd.
This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
-->

<link rel="import" href="../polymer/polymer-element.html">
<link rel="import" href="../polymer/lib/mixins/gesture-event-listeners.html">
<link rel="import" href="../iron-dropdown/iron-dropdown.html">
<link rel="import" href="../iron-media-query/iron-media-query.html">
<link rel="import" href="../vaadin-themable-mixin/vaadin-themable-mixin.html">
<link rel="import" href="vaadin-date-picker-overlay.html">
<link rel="import" href="vaadin-date-picker-mixin.html">
<link rel="import" href="vaadin-date-picker-helper.html">
<link rel="import" href="../vaadin-text-field/vaadin-text-field.html">
<link rel="import" href="vaadin-date-picker-styles.html">

<dom-module id="vaadin-date-picker">
  <template>
    <style>
      :host {
        display: inline-block;
      }

      :host([opened]) {
        pointer-events: auto;
      }

      [part="text-field"] {
        min-width: 100%;
      }

      [part="overlay"] {
        height: 100vh;
        width: 420px;
      }

      [part="clear-button"],
      [part="toggle-button"] {
        font-family: 'vaadin-date-picker-icons';
      }

      [part="clear-button"]::before {
        content: "\e901";
      }

      [part="toggle-button"]::before {
        content: "\e902";
      }

      :host([disabled]) [part="clear-button"],
      :host([disabled]) [part="toggle-button"],
      :host([readonly]) [part="clear-button"],
      :host([readonly]) [part="toggle-button"],
      :host(:not([has-value])) [part="clear-button"] {
        display: none;
      }
    </style>


    <vaadin-text-field id="input"
        role="application"
        autocomplete="off"
        on-focus="_focus"
        value="{{_userInputValue}}"
        invalid="[[invalid]]"
        label="[[label]]"
        name="[[name]]"
        placeholder="[[placeholder]]"
        required="[[required]]"
        disabled="[[disabled]]"
        readonly="[[readonly]]"
        error-message="[[errorMessage]]"
        aria-label$="[[label]]"
        part="text-field"
      >
      <slot name="prefix" slot="prefix"></slot>
      <div part="clear-button" slot="suffix" on-tap="_clear" role="button" aria-label$="[[i18n.clear]]"></div>
      <div part="toggle-button" slot="suffix" on-tap="_toggle" role="button" aria-label$="[[i18n.calendar]]" aria-expanded$="[[_getAriaExpanded(opened)]]"></div>
    </vaadin-text-field>

    <iron-dropdown
        id="dropdown"
        fullscreen$=[[_fullscreen]]
        allow-outside-scroll
        on-iron-overlay-opened="_onOverlayOpened"
        on-iron-overlay-closed="_onOverlayClosed"
        on-iron-overlay-canceled="_preventCancelOnComponentAccess"
        opened="{{opened}}"
        no-auto-focus>
      <vaadin-date-picker-overlay
          id="overlay" i18n="[[i18n]]"
          fullscreen$="[[_fullscreen]]"
          label="[[label]]"
          selected-date="{{_selectedDate}}"
          slot="dropdown-content"
          focused-date="{{_focusedDate}}"
          show-week-numbers="[[showWeekNumbers]]"
          min-date="[[_minDate]]"
          max-date="[[_maxDate]]"
          role="dialog"
          part="overlay">
      </vaadin-date-picker-overlay>
    </iron-dropdown>

    <iron-media-query
        query="[[_fullscreenMediaQuery]]"
        query-matches="{{_fullscreen}}">
    </iron-media-query>
  </template>

  <script>
    if (!Polymer.Element) {
      throw new Error(`Unexpected Polymer version ${Polymer.version} is used, expected v2.0.0 or later.`);
    }

    {
      /**
       *
       * `<vaadin-date-picker>` is a date selection field which includes a scrollable
       * month calendar view.
       * ```html
       * <vaadin-date-picker label="Birthday"></vaadin-date-picker>
       * ```
       * ```js
       * datePicker.value = '2016-03-02';
       * ```
       * When the selected `value` is changed, a `value-changed` event is triggered.
       *
       *
       * ### Styling
       *
       * The following shadow DOM parts are available for styling:
       *
       * Part name | Description | Theme for Element
       * ----------------|----------------|----------------
       * `text-field` | Input element | vaadin-date-picker
       * `clear-button` | Clear button | vaadin-date-picker
       * `toggle-button` | Toggle button | vaadin-date-picker
       * `overlay` | The overlay element | vaadin-date-picker
       * `overlay` | The overlay element | vaadin-date-picker-light
       * `overlay-header` | Fullscreen mode header | vaadin-date-picker-overlay
       * `label` | Fullscreen mode value/label | vaadin-date-picker-overlay
       * `clear-button` | Fullscreen mode clear button | vaadin-date-picker-overlay
       * `toggle-button` | Fullscreen mode toggle button | vaadin-date-picker-overlay
       * `years-toggle-button` | Fullscreen mode years scroller toggle | vaadin-date-picker-overlay
       * `months` | Months scroller | vaadin-date-picker-overlay
       * `years` | Years scroller | vaadin-date-picker-overlay
       * `toolbar` | Footer bar with buttons | vaadin-date-picker-overlay
       * `today-button` | Today button | vaadin-date-picker-overlay
       * `cancel-button` | Cancel button | vaadin-date-picker-overlay
       * `month` | Month calendar | vaadin-date-picker-overlay
       * `year-number` | Year number | vaadin-date-picker-overlay
       * `year-separator` | Year separator | vaadin-date-picker-overlay
       * `month-header` | Month title | vaadin-month-calendar
       * `weekdays` | Weekday container | vaadin-month-calendar
       * `weekday` | Weekday element | vaadin-month-calendar
       * `week-numbers` | Week numbers container | vaadin-month-calendar
       * `week-number` | Week number element | vaadin-month-calendar
       * `date` | Date element | vaadin-month-calendar
       *
       * If you want to replace the default input field with a custom implementation, you should use the
       * [`<vaadin-date-picker-light>`](#vaadin-date-picker-light) element.
       *
       * @memberof Vaadin
       * @mixes Vaadin.ThemableMixin
       * @mixes Vaadin.DatePickerMixin
       * @mixes Polymer.GestureEventListeners
       * @demo demo/index.html
       */
      class DatePickerElement extends Vaadin.ThemableMixin(Vaadin.DatePickerMixin(Polymer.GestureEventListeners(Polymer.Element))) {

        static get is() {
          return 'vaadin-date-picker';
        }

        static get properties() {
          return {
            /**
             * Set to true to disable this element.
             */
            disabled: {
              type: Boolean,
              value: false,
              reflectToAttribute: true
            },

            /**
             * The error message to display when the input is invalid.
             */
            errorMessage: String,

            /**
             * A placeholder string in addition to the label. If this is set, the label will always float.
             */
            placeholder: String,

            /**
             * Set to true to make this element read-only.
             */
            readonly: {
              type: Boolean,
              value: false,
              reflectToAttribute: true
            },

            /**
             * This property is set to true when the control value invalid.
             */
            invalid: {
              type: Boolean,
              reflectToAttribute: true,
              notify: true,
              value: false
            },

            _userInputValue: String
          };
        }

        static get observers() {
          return [
            '_userInputValueChanged(_userInputValue)'
          ];
        }

        ready() {
          super.ready();

          // In order to have synchronized invalid property, we need to use the same validate logic.
          Polymer.RenderStatus.afterNextRender(this, () => this._inputElement.validate = () => {});
        }

        _clear(e) {
          e.stopPropagation();
          this.value = '';
          this.close();
        }

        _toggle(e) {
          e.stopPropagation();
          this[this.$.dropdown.opened ? 'close' : 'open']();
        }

        _input() {
          return this.$.input;
        }

        set _inputValue(value) {
          this._inputElement.value = value;
        }

        get _inputValue() {
          return this._inputElement.value;
        }

        _getAriaExpanded(opened) {
          return Boolean(opened).toString();
        }
      }

      customElements.define(DatePickerElement.is, DatePickerElement);

      /**
       * @namespace Vaadin
       */
      window.Vaadin = window.Vaadin || {};
      Vaadin.DatePickerElement = DatePickerElement;
    }
  </script>
</dom-module>

my-view1.html页面上的代码返回yyyy-mm-dd:

<!--
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="shared-styles.html">
<link rel="import" href="../bower_components/vaadin-grid/vaadin-grid.html">
<link rel="import" href="../bower_components/vaadin-date-picker/vaadin-date-picker.html">
<link rel="import" href="../bower_components/paper-input/paper-input.html">
<link rel="import" href="../bower_components/paper-button/paper-button.html">
<link rel="import" href="../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="../bower_components/iron-icons/iron-icons.html">
<link rel="import" href="../bower_components/app-storage/app-localstorage/app-localstorage-document.html">






<dom-module id="my-view1">
  <template>
    <style include="shared-styles">
      :host {
        display: block;

        padding: 10px;
      }
      .form {
        display: flex;
        flex-direction: column;
      }
      .form paper-input {
        flex: 1;
        margin-right: 10px;
      }
      .form vaadin-date-picker {
        flex: 1;
        margin-top: 10px;

      }
      .form paper-button {
        margin-top: 10px;
        align-self: flex-end;
      }

    </style>
    <div class="card">
      <div class="form">
      <paper-input label="Sum" value="{{todo.task}}" auto-validate placeholder="Suma" required pattern="[0-9]*" error-message="Numbers only"></paper-input>
      <vaadin-date-picker label="Date" value="{{todo.due}}"></vaadin-date-picker>
      <paper-button raised on-tap="_addToDo">Add</paper-button>
      </div>
<br>
      <vaadin-grid style="display: flex;" id="grid" items={{todos}}>


            <vaadin-grid-column width="calc(50% - 90px)">
              <template class="header">Sum</template>
              <template>{{item.task}}</template>
          </vaadin-grid-column>

    <vaadin-grid-column width="30%">
      <template class="header" >Date</template>
      <template>{{item.due}}</template>
    </vaadin-grid-column>
    <vaadin-grid-column width="10%">
      <template><paper-icon-button icon="close" on-tap="_remove"></paper-icon-button></template>
    </vaadin-grid-column>

  </vaadin-grid>
    </div>
<app-localstorage-document key="todos" data="{{todos}}">
</app-localstorage-document>
<center> Copyright &copy; 2017 Dragosh.</center>
  </template>



  <script>
    class MyView1 extends Polymer.Element {
      static get is() { return 'my-view1'; }

      static get properties() {
        return {
          todo: {
            type: Object,
            value: () => { return {} }
          },
          todos: {
            type: Array,
            value: () => []
          }
        };
      }

      _addToDo() {
        console.log(this.todo)

      };

      _remove(e) {
        var index = this.todos.indexOf(e.model.item);
          this.splice('todos', index, 1)
          this.$.grid.clearCache();


      };


    }


    window.customElements.define(MyView1.is, MyView1);

  </script>
</dom-module>

如果我在vaadin-date-picker中选择日期,并在SUM输入中不输入SUM,则在输入中显示为dd-mm-yyyy,但我的控制台会记录yyyy-mm-dd。

以下是截图,以便您更好地了解: DatePicker 这有什么不对?我在哪里可以更改日期格式? 谢谢!

1 个答案:

答案 0 :(得分:1)

您必须通过执行 Sugar.Date.setLocale('nl')例如

来使用Sugar.js设置语言环境。
let dp=this.shadowRoot.querySelector('#' + 'dp')
    dp.i18n = {
                week: 'week',
                calendar: 'calendar',
                clear: 'clear',
                today: 'today',
                cancel: 'cancel',
                firstDayOfWeek: 1,
                monthNames:
                  'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
                weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
                weekdaysShort: 'su_mo_tu_we_th_fr_sa'.split('_'),
                formatDate: function(date) {
                  **Sugar.Date.setLocale('nl');**
                  // Sugar Date expects a native date. The `date` is in format `{ day: ..., month: ..., year: ... }`
                  return Sugar.Date.format(Sugar.Date.create(date), '{short}');
                },
                formatTitle: function(monthName, fullYear) {
                  return monthName + ' ' + fullYear;
                },
                parseDate: function(dateString) {
                  const date = Sugar.Date.create(dateString);
                  return {
                    day: date.getDate(),
                    month: date.getMonth(),
                    year: date.getFullYear()
                  };
                }
              };