1

I'm working on legacy system and in DB the birthday is coming this way '1992-05-18' in json. I am using AngularJS and when applying the data binding of this variable in an input type = "date", of an update form, it is necessary to instantiate a Date object. Like this:

//person.byrthday = '1992-04-26'
var person.birthday = new Date (person.birthday); 
// after person.byrthday = '1992-04-25T00:00:00.000Z'

How can I solve this problem through Front End in an elegant way, without "breaking" two way data binding?

I find myself in Brasil UTC -03:00

georgeawg
  • 48,608
  • 13
  • 72
  • 95
cpll
  • 157
  • 2
  • 10
  • Your best bet is probably to use a library like Moment.js to handle dates. – VLAZ Oct 19 '18 at 13:18
  • 1
    If your offset is -0300, then given `new Date('1992-04-26')` the result will be a Date for '1992-04-26T00:00:00.000Z'. Treating it as UTC only shifts local dates by the host timezone offset (-0300 apparently), which will be '1992-04-25T21:00:00.000-0300'. – RobG Oct 19 '18 at 13:45

1 Answers1

1

There are a few ways to solve this problem. A quick and dirty solution could be to leverage moment.js. You can convert the response from the API to a true date format this way.

If you don't want to use an additionally library, you can make a function to parse the date string. You can do the following to parse is to become a correct date:

var dateSplit = person.birthday.split('-');
var mydate = new Date(dateSplit[0], dateSplit[1] - 1, dateSplit[2]); 
person.birthday= mydate;

Take note that the month index starts at 0 (aka January=0). Hopefully this helps.

CoolestNerdIII
  • 770
  • 4
  • 10