0

I'm trying to figure out how best to compare dates in Angular 2 and TypeScript 1.8.7.

Given:

startDate: Date;
endDate: Date;

if(this.startDate.getUTCMilliseconds() === this.endDate.getUTCMilliseconds()){
     //do stuff here
} else {
     // do something else here
}

This will return an error like "startDate.getUTCMilliseconds is not a function..."

Does somebody have a best practice? Thanks,

LargeDachshund
  • 916
  • 3
  • 12
  • 25
  • `{{+startDate == +endDate}}` (unary `+`) doesn't work in binding expressions though https://github.com/angular/angular/issues/7964 – Günter Zöchbauer Apr 20 '16 at 06:23
  • See also https://plnkr.co/edit/EFsbEl?p=preview (3 and 4 demonstrated how unary `+` works differently when applied in template (no effect) and in code. – Günter Zöchbauer Apr 20 '16 at 06:33

3 Answers3

1

Date object method to get milliseconds is called getTime.

kemsky
  • 14,727
  • 3
  • 32
  • 51
  • Nice try. But, we're dealing with javascript dates. This is way too logical. If there's some interference from Typescript, I don't have a clue. Intellisense is comfortable with getTime, but Chrome is screaming that getTime is not a function. – LargeDachshund Apr 20 '16 at 03:53
  • `someDate.getTime()` works fine for me in Chrome. – Günter Zöchbauer Apr 20 '16 at 06:20
  • @LargeDachshund Did you solve this? I have the same problem – Wouter Vanherck May 02 '17 at 12:43
  • Wouter, I have not. I needed this logic for field validation. It became such a pain that I gave up. What's so painful is that you'd think something like time would be quite determinant. Instead, there are tons of formatted dates that pass for a date. So, I took a pass on this issue. Thanks for making me relive this nightmare. – LargeDachshund May 03 '17 at 23:06
  • `getTime` and any other method of `Date` type does not work for me – Amir Choubani Jun 07 '18 at 10:21
1

You can compare Date objects directly, with operators like <, >, and ==.

this.startDate == this.endDate
Matt C
  • 4,470
  • 5
  • 26
  • 44
  • While this appears to be the right answer, I can't give the "green check mark" because of this test: if this.endDate = new Date("0001-01-01T00:00:00") and this.startDate is the minimum date, the condition should return true. Instead, the condition returns false. This is fitting because dates in Java and javascript are inscrutable. – LargeDachshund Apr 20 '16 at 03:48
  • @LargeDachshund What test? – Matt C Apr 20 '16 at 03:49
0

I know it's irrelevant and not what you asked for, but use angular-moment / momentjs. Dates in JS are a complete mess.

user1027620
  • 2,745
  • 5
  • 37
  • 65
  • Dates in general, seem like a complete mess. If there's a best practice for boxing/unboxing dates in TypeScript objects, I'm all ears. That's what I'm driving at. – LargeDachshund Apr 20 '16 at 03:19