Mir
Mir

Reputation: 1613

Create an input type="date" in Ember

I'm trying to create an <input type="date"/> in Emberjs and I have two problems:

  1. In my country the date is displayed as DD-MM-YYYY format while the date field requires a MM-DD-YYYY format (and then the browser displays it according to its locale). So the date should be formatted in one way if the browser supports the date input field and in the other way if not
  2. The date is bound to a Date object

I'm using Momentjs for formatting and Ember Data.

I'm trying to extend Ember.TextField like this:

App.DateField = Ember.TextField.extend
  value: ( (key, value) ->
    if value?
      if /Date/.test value.constructor #I assume that if the passed value is a Date object then it is arriving directly from the model
        if Modernizr.inputtypes.date
          moment(value).format('YYYY-MM-DD')
        else
          moment(value).format('DD-MM-YYYY')
      else # if the passed value is not a Date object then the user is typing into the form
        if Modernizr.inputtypes.date
          value = new Date('value')
        else
          value

  ).property()

  type: 'date'

For browsers with date input supports this works. For the other browsers the date is correctly displayed, but it is saved as a (wrong formatted) string in the model.

How can I maintain the correct formatting while still using Date objects in the backend?

Demo

Update

Thanks to the blog post provided in the accepted answer I was able to update the demo to do what I want (with some weirdnesses, but not relevant at this time)

Demo2

Upvotes: 5

Views: 3958

Answers (2)

ianpetzer
ianpetzer

Reputation: 1838

Have look at these two blog posts:

This is a simple date picker: http://hawkins.io/2013/06/datepicker-in-ember/ This one uses the bootstrap date picker http://hawkins.io/2013/06/fancy-ember-datepicker-with-twitter-bootstrap/

Hopefully that will help

Upvotes: 2

Darshan Sawardekar
Darshan Sawardekar

Reputation: 5075

I don't see any parsing for the string use case. You will need to use something like Date.parse to convert the string entered by the user into a Date object.

if Modernizr.inputtypes.date
  value = new Date(value)
else
  value = Date.parse(value)

Upvotes: 2

Related Questions