Saturday, April 6, 2013

Get Date..!


In many cases we want to use different dates (today's date / future date/ past date) with different formats.

Example:

  1. Task due date you want to fill 5 days from current date with dd-MM-yyyy format.
  2. You want to add today's date automatically to some field with MMM/dd/yy format.
  I'm just writing a java method which will take two arguments period (no of days) & format of date.

    For Getting today's date pass period as 0 , for getting future date pass period as positive and negative number for getting past date. 
<>
 Logic

public String getDate(int period,String format)
{
     Calendar currentDate = Calendar.getInstance();
     SimpleDateFormat formatter= new SimpleDateFormat(format);
     currentDate.add(Calendar.DAY_OF_MONTH, period);
     String date = formatter.format(currentDate.getTime());
     return date;
}
//Parameters :
//period : no of days gap between the current and desired date
//format : Format of the date (Ex : dd/MM/yyyy . yyyy MMM dd)

Output :
Current date & Time is :
No of days Format Output
0 "MM/dd/yyyy"
5 "MM/dd/yyyy"
-3 "MM/dd/yyyy"



Happy coding :)

Regards,
SantoshSarma

12 comments:

  1. hi...could u please give a brief...Im not getting u sir

    ReplyDelete
    Replies
    1. Hi Avanthi,

      Sometimes you may want to get Dates dynamically based on current date. I mean 2 days later date or 5 days back date. In that case you just need to pass one parameter to above method 2 or -5 respectively.

      In different applications we see/use different formats of dates based on the requirement. So by using the above method you can specify date format also.

      Ex :
      dd/MM/yyyy
      dd-MMM-yyyy
      MMM,dd yyyy
      yyyy_MM_dd

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. getDate(24,"d MMM yyyy");

      Call above method like above because May 3 2013 is 24 days later from today (Apr 8 2013)

      Delete
    2. This comment has been removed by the author.

      Delete
  3. From the calendar I able to execute the process if i'm selecting the date of this months.If i'm using next month then process is not getting

    ReplyDelete
    Replies
    1. I didn't get what you are asking ? Could you please elaborate at my mail ?

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. In Schedule Post "Calendar will be there sir

    ReplyDelete
    Replies
    1. FYI :

      With the given code in post you can't choose date from Calendar but, you can directly type date value in that field If you've access to write date in that field.

      Delete
  7. thank you sir for valuable ideas .even for drop downlist i used face many problem because of ur blogs ,dat probelm is solved sir thanks for valuable ideas

    ReplyDelete

Note: Only a member of this blog may post a comment.