Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>How would you get it in months?</p> <p>Each month has a different number of days, so what would you do?</p> <p>You can get back the date this represents from now by doing:</p> <pre><code>println duration.from.now </code></pre> <p>Or, you can get the date that represents in the past by doing:</p> <pre><code>println duration.ago </code></pre> <p>And I guess you could work it out from there, but there is no in-built functionality for normalising a TimeDuration based on a given date</p> <hr> <h2>Edit</h2> <p>This sort of thing rolls from one date in the past to the specified date. I haven't done any real testing on it though, so you should take care and test the life out of it before using it in anything important...</p> <pre><code>import static java.util.Calendar.* import groovy.time.DatumDependentDuration import groovy.time.TimeCategory DatumDependentDuration getAge( Date dob, Date now = new Date() ) { dob.clearTime() now.clearTime() assert dob &lt; now Calendar.instance.with { c -&gt; c.time = dob def (years, months, days) = [ 0, 0, 0 ] while( ( c[ YEAR ] &lt; now[ YEAR ] - 1 ) || ( c[ YEAR ] &lt; now[ YEAR ] &amp;&amp; c[ MONTH ] &lt;= now[ MONTH ] ) ) { c.add( YEAR, 1 ) years++ } while( ( c[ YEAR ] &lt; now[ YEAR ] ) || ( c[ MONTH ] &lt; now[ MONTH ] &amp;&amp; c[ DAY_OF_MONTH ] &lt;= now[ DAY_OF_MONTH ] ) ) { // Catch when we are wrapping the DEC/JAN border and would end up beyond now if( c[ YEAR ] == now[ YEAR ] - 1 &amp;&amp; now[ MONTH ] == JANUARY &amp;&amp; c[ MONTH ] == DECEMBER &amp;&amp; c[ DAY_OF_MONTH ] &gt; now[ DAY_OF_MONTH ] ) { break } c.add( MONTH, 1 ) months++ } while( c[ DAY_OF_YEAR ] != now[ DAY_OF_YEAR ] ) { c.add( DAY_OF_YEAR, 1 ) days++ } new DatumDependentDuration( years, months, days, 0, 0, 0, 0 ) } } println getAge( Date.parse( 'dd/MM/yyyy', '11/10/2000' ) ) // Prints: '12 years, 2 months, 30 days' </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload