0

I'm tasked with writing a web portal for a legacy application that was written in Visual Foxpro. I have to validate a pregnancy due date. The rule is that it can't be more than 9 months from the current date. I've already tried to argue that this is too vague and that it needs to be in days or weeks, but I was told that I have to mimic the legacy software.

Here's what the code in VSP is doing:

maxValueForDueDate = GOMONTH(DATE() , 9)

According to MSDN GOMONTH() handles edge cases as follows:

SET CENTURY ON
STORE GOMONTH({^1998-02-16}, 5) TO gdDeadLine

CLEAR
? gdDeadLine  && Displays 07/16/1998
? GOMONTH({^1998-12-31}, 2)  && Displays 02/28/1999
? GOMONTH({^1998-12-31}, -2)  && Displays 10/31/1998

As you can see adding 2 months to December 31st does not result in March 2nd, unfortunately that's exactly what the following javascript does:

var dDate = new Date('1998-12-31');
dDate.setMonth(dDate.getMonth() + 2);
alert(dDate.toDateString()); // results in - Tue Mar 02 1999

Does anyone have a javascript function handy that they've written for this scenario? I've googled around, but haven't found what I need. I'm limited in my third-party usage to JQuery.

Nathan
  • 1,080
  • 7
  • 16

2 Answers2

1

Add the number of milliseconds (or seconds or hours or days) in 2 "full months" (that is, 30 days x 24 hours). The idea is that the entire date is shifted, and not just the single [month] component. For example:

var a = new Date('1998-12-31')
var ms_in_month = 30 * (24 * 60 * 60) * 1000
var b_ticks = (+a) + 2 * ms_in_month
var b = new Date(b_ticks)
alert(b) // Sun Feb 28 1999 16:00:00 GMT-0800 (Pacific Standard Time)

The (+a) coerces the Date to a number which results in the number of milliseconds since epoch. (This could also be written as a.milliseconds). Then new Date(millis_since_epoch) does the reverse and creates a Date from the epoch offset.

Disclaimer: I am not sure what the exact rules for GOMONTH are , and it might use the "30.5 days in a month heuristic" (365/12 = 30.41) or another variation. I suspect it does not account for the month durations (the documentation does state that "-1 [month] means -31 days") or leap years ..

  • I'm not sure why this works but it does, so thank you. So 30 days times 2 months averages out the days in a month? – Nathan Aug 13 '12 at 19:55
  • @Nathan 30.5 days-per-month would be a better average over a year. Roughly. I am not sure what VFP uses though. If using non-whole-days (or caring about leap seconds) then the starting time should be biased to "mid day" to account for minor inacurracies. –  Aug 13 '12 at 20:31
0

You can look at the open source javascript date library Datejs

If you cannot add this file, you can at least look at the code to see how the edge cases are handled.

Scorpion-Prince
  • 3,574
  • 3
  • 18
  • 24