mz_01
mz_01

Reputation: 495

Add timespan to a date?

Can anyone think of an efficient way of adding a timespan to a date?

Something like the following:

    <cfset foo = now() + createTimeSpan(15,12,30,30)>

IIRC in a .NET-based CFML engine I could simply use date.add(timespan), but I can't remember the equivalent Java shortcut right now.

Thanks in advance.

Upvotes: 0

Views: 1074

Answers (1)

Adam Cameron
Adam Cameron

Reputation: 29870

What actually are you asking here? On one hand you've tagged it as a CF question and use CFML which answers your own question; then you start asking about a Java short cut?

If you want to know how to do it in CFML, then your code sample is how you do it in CFML.

If you want to know how to add a CF timespan value (which is just a numeric representation of a number of days) to a Java date, then it seems to be slightly trickier, because the Calendar methods I can find all add the component parts of the timespan, not the whole timespan.

This code demonstrates possibly all the answers you're after (except how to do it in one hit with a Java date/calendar):

<cfset dTs = now()><!--- grab now --->
<cfset fTimespan = createTimeSpan(15,12,30,30)><!--- make a timespan --->
<cfset fLater = dTs + fTimespan><!--- add the timespan to now yields a float --->
<cfset sLater = dateFormat(fLater, "yyy-mm-dd") & " " & timeformat(fLater, "HH:MM:SS")><!--- but you can treat a float as a date/time --->
<cfset dLater = createOdbcDateTime(fLater)><!--- or convert it back to a date object --->

<cfset jCal = createObject("java", "java.util.GregorianCalendar").init()><!--- java.util.Date is basically deprecated in favour of calendars --->
<cfset jCal.add(jCal.DAY_OF_MONTH, 15)><!--- one needs to set each part of the timespan separately --->
<cfset jCal.add(jCal.HOUR_OF_DAY, 12)>
<cfset jCal.add(jCal.MINUTE, 30)>
<cfset jCal.add(jCal.SECOND, 30)>
<cfset sJCal = jCal.getTime()><!--- this gets a string that CF can use as a date back out of the calendar --->
<cfset bIsDate = isDate(sJCal)><!--- demonstrate that last statement to be true --->
<cfdump var="#variables#"><!--- and all the results --->

Does that answer whatever your question actually was?

Upvotes: 3

Related Questions