Forum Discussion

tmarshall's avatar
tmarshall
Advisor
8 years ago

Dynamically get date in LIQL call through API

Hi,    I've read the following: https://community.lithium.com/t5/Developers-Discussion/Getting-correct-date-format-for-use-in-LiQL/m-p/180275#M7166 https://community.lithium.com/t5/Developers-Dis...
  • PerBonomi's avatar
    PerBonomi
    8 years ago

    Just a suggestion; I like to plan ahead and be ready for change. Hard code sucks in the future.

     

    With something like this you leave yourself a choice:

    • Automatically query back x days, or
    • Add a variable to the request url for a specific date, or
    • Add a variable to the request url for a specific number of days to go back
    <#assign date_before_set = http.request.parameters.name.get("date_before", "")?string /> <!-- use the url to determine what date you want to check back to -->
    <#assign days_back_set = http.request.parameters.name.get("days_back", "")?string /> <!-- use the url to determine how many days back to look at -->
    
    <#assign date_today_for_query = .now?datetime?string["yyyy-MM-dd"]/>
    
    <#if date_before_set == ""> <!-- if you didn't pass a hard date in the url then continue -->
    	<#if days_back_set == ""> <!-- if you didn't pass a specific number of days then check variable from code, e.g. 30 days -->
    		<#assign days_back = 30/>
    	<#else>
    		<#assign days_back = days_back_set?number/> <#-- make sure the number passed in the url isn't seen as string; this can bork the query -->
    	</#if>
    	<#assign date_today_long = .now?long/>
    	<#assign date_before_long = date_today_long - ( days_back * 1000 *60 *60 *24 ) />
    	<#assign date_before = date_before_long?number_to_datetime?string["yyyy-MM-dd"]/>
    </#if>
    Test:
    Today: ${date_today_for_query}<br/>
    Before: ${date_before}

    Now you can use this in your query (post_time as example):

    ... WHERE post_time >= ${date_before}T00:00:00.000 AND post_time <= ${date_today_for_query}T00:00:00.000 ...

     

    If you call just the url you will go back 30 days from today.

    But if you add url?date_before_set=2016-12-30 you can go back to any date you want without much hassle.

    And, if you add url?days_back_set=31 you can go back any specific number of days you want without much hassle.

     

    Like I said, it can pay to plan ahead and not have to alter much code, but it's completely optional.