I have a javascript snippet which populates the cookie value. Now i need to fetch this value inside a controller.

function setCookie(c_name,value,exdays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
}

this is the button onclick:

<button type="button" class="btn btn-default" data-dismiss="modal" 
        onclick="setCookie('apex__datecookie', 
                           Math.round(new Date().getTime() / 1000),100)">
        Close
</button>

class:

System.Cookie cookie = ApexPages.currentPage().getCookies().get('datecookie');   
if (cookie != null) {
    String field = cookie.getValue();
    Integer date= cookie.getMaxAge();
}

I am getting the cookie value as some number inside the log. How can i convert this into date value?

  • 2
    String field = cookie.getValue(); Long field_long = Long.valueOf(field); DateTime result_date = DateTime.newInstance(field_long); // would convert ticks to datetime. – kurunve Oct 24 '16 at 12:55
  • @kurunve You may like to put that as an answer – Mohith Shrivastava Oct 24 '16 at 14:41

Javascript code new Date().getTime() would return time in ticks (which are amount of milliseconds between 1 january 1970 and now)

To convert it to DateTime, next code (DateTime static method) may to be used in Apex method:

String field = cookie.getValue();
Long field_long = Long.valueOf(field);
DateTime result_date = DateTime.newInstance(field_long);

Documentation about DateTime class is here

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.