简体   繁体   中英

angularjs - confusion with date formats

I am super confused with date formats and need some clarifications. I am trying to pre-populate a form with a date and have set $scope.selectedDate = c.data.Appt.enrolled.start_date;

In my console, c.data.Appt.enrolled.start_date is a string:

在此处输入图片说明

However, when I set $scope.selectedDate to that, nothing shows up.

Conversely, if I add new Date in front

(new Date(c.data.Appt.enrolled.start_date))

a date shows up, but it is one day before (April 24, 2018).

In addition to that, when I try to insert the "new Date" version into a function (even though it isn't the correct date), I get a warning in the console saying "Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release."

Can someone explain how I should format the dates so I: 1) get the correct date and not one day prior and 2) am able to plug it into a function without getting that warning?

Thanks!

Since the date is a string with no time zone information (just the date) JavaScript Date parser will treat it as universal(UTC, which is in Greenwich Mean Time) time at 00:00 hours. Then it will subtract the offset of your locale's timezone in hours, and will result in the date being a few hours before or after the day you actually want. This is a common point of confusion.

The best way to solve this is to parse the date manually:

function localDate(dateString) {
  var d = dateString.split(/\D/);
  return new Date(d[0], d[1]-1, d[2]);
}

See this question for more information: Javascript: parse a string to Date as LOCAL time zone

Moment.js gives that warning because it's considered bad practice to rely on the string parsing that new Date() does since it will have different results in different browsers (IE\\Firefox\\Etc.). It's more cross-browser friendly to build the date using this form: new Date(year, month, day) . (Note that the month starts at zero, not 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM