In many cases we want to use different dates (today's date / future date/ past date) with different formats.
Example:
- Task due date you want to fill 5 days from current date with dd-MM-yyyy format.
- 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.
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