Forum Discussion

vishwajeet_hol's avatar
10 years ago

'Get 30 days ago' and 'one year ago' date in freemarker

Hi,

 

I am getting current date using below code :

<#assign aDateTime = .now>
<#assign aDate = aDateTime?date>
current date: ${aDate?iso_utc}

How to 'get 30 days ago' and 'one year ago' date using freemarker ?

 

Thank you.

 

Regards,

Vishwajeet.

  • vishwajeet_hol - Well, for that you'll have to create a function. Here is a dummy function, you can use it accordingly.

     

    <#function relativeTime time> <!-- pass the post time to this freemarker function -->
    <#assign current_time = .now?long>
    <#assign action_time = time?long> <!-- this is the post time you pass to the function -->
    <#assign diff = current_time - action_time> <!-- get the difference in post time and current time-->

    <#if diff == 0>
    <#return 'now'>
    <#elseif (diff > 0)>
    <#assign day_diff = diff / 86400000>
    <#assign day_diff = day_diff?floor>

    <#if (day_diff == 0)>
    <#if (diff < 60000)>
    <#return 'just now'>
    </#if>
    <#if (diff < 120000)>
    <#return '1 minute ago'>
    </#if>
    </#if>

    <#if (day_diff < 7)>
    <#return day_diff + ' days ago'>

    </#if>
    <#if (day_diff < 31)>
    <#assign weeks = (day_diff / 7)?ceiling>
    <#if (weeks == 1)>
    <#return 'Last week.'>
    </#if>
    <#return weeks + ' weeks ago'>
    </#if>

    </#if>
    <#return action_time?number_to_date>
    </#function>

    I hope this helps.

    • vishwajeet_hol's avatar
      vishwajeet_hol
      Expert

      Got the solution :

      <#assign currentDate = .now>
      Current Date : ${currentDate?date}<br>
      <#assign numberOfDays = 30?long>
      <#assign timeInMillisecond = (1000 * 60 * 60 * 24 * numberOfDays) >
      <#assign aDate = currentDate?long - timeInMillisecond?long>
      <#assign Diff = aDate?long>
      <#assign thirtyDaysBeforeDate = Diff?number_to_date>
      <br>Date before ${numberOfDays} Days : ${thirtyDaysBeforeDate}<br>
      <br>Date before ${numberOfDays} Days in UTC format : ${thirtyDaysBeforeDate?iso_utc}<br>

       

       

      Thanks,

      Vishwajeet