Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Routine to give difference between two dates as words (years, months, weeks and days)

Status
Not open for further replies.

GriffMG

Programmer
Mar 4, 2002
6,333
FR
I needed to express the difference between two dates as a string with years, months, weeks and days being split out and found very little to help do this in VFP.

The trick - it seems to me - is to calculate the number of months first, using GoMonth() iteratively. Years are always 12 months, so they can be split off.
Then 'rebase' the earlier date to the whole months position, and calculate the number of days remaining - then the weeks can be split off as these are always 7 days.
This can then be used to work out the remaining days.

Might not be any use to anyone but me... but here it is
Code:
FUNCTION DATEDIFFASWORDS
	PARAMETERS m.DATE1,m.DATE2
	PRIVATE m.DATE1,m.DATE2, m.YEARS,m.MONTHS,m.WEEKS,m.DAYS,m.TEMP,m.STRING
	m.YEARS = 0
	m.MONTHS = 0
	m.WEEKS =0
	m.DAYS = 0
	** swap dates if needs be m.date2 should be the greater
	IF m.DATE1 > m.DATE2
		m.TEMP = m.DATE1
		m.DATE1 = m.DATE2
		m.DATE2 = m.TEMP
	ENDIF
	m.MONTHS = 0
	IF GOMONTH(m.DATE1, 1) < m.DATE2
		DO WHILE GOMONTH(m.DATE1, m.MONTHS) < m.DATE2
			m.MONTHS = m.MONTHS + 1
		ENDDO
		m.MONTHS = m.MONTHS-1
	ENDIF

	m.DATE1 = GOMONTH(m.DATE1,m.MONTHS)
	m.DAYS = m.DATE2-m.DATE1
	m.WEEKS = INT(m.DAYS/7)
	m.DAYS = m.DAYS - (m.WEEKS * 7)
	m.YEARS = INT(m.MONTHS/12)
	m.MONTHS = m.MONTHS - (m.YEARS * 12)
	m.STRING = ""
	IF m.YEARS > 0
		m.STRING = ALLTRIM(STR(m.YEARS)+ " Year"+IIF(m.YEARS>1,"s",""))
	ENDIF
	IF m.MONTHS > 0
		m.STRING = ALLTRIM( m.STRING +" "+ALLTRIM(STR(m.MONTHS))+" Month"+IIF(m.MONTHS>1,"s",""))
	ENDIF
	IF m.WEEKS > 0
		m.STRING = ALLTRIM( m.STRING +" "+ALLTRIM(STR(m.WEEKS))+" Week"+IIF(m.WEEKS>1,"s",""))
	ENDIF
	IF m.DAYS > 0
		m.STRING = ALLTRIM( m.STRING +" "+ALLTRIM(STR(m.DAYS))+" Day"+IIF(m.DAYS>1,"s",""))
	ENDIF

	RETURN(m.STRING)

Regards

Griff
Keep [Smile]ing

There are 10 kinds of people in the world, those who understand binary and those who don't.

I'm trying to cut down on the use of shrieks (exclamation marks), I'm told they are !good for you.
 
I have created a FAQ for this, and improved the code very slightly - waiting for number...
Regards

Griff
Keep [Smile]ing

There are 10 kinds of people in the world, those who understand binary and those who don't.

I'm trying to cut down on the use of shrieks (exclamation marks), I'm told they are !good for you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top