Java Date Utility methods: Getting past/future date from days

Date manipulation is required in everyday Java programming. Creating a date instance for a past or future date is required at many places where we are trying to have a date range.
The Java Utility method getDateBeforeDays() returns a java.util.Date instance with a date before number of days specified.

JAVA Date Utility Tutorial Java,JAVA Date Utility, This program Demonstrates the proper use of Date functionality,Date and Time, get past and future dates, util methods to get date from past/previous days. util method/function for getting a future date. java date utilities, java date utility, get java date after days, hours, minutes, seconds, java calculate future date, java calculate past date,

/**
* This utility method returns a past date before number of days.
* @param days
* @return
*/
public static Date getDateBeforeDays(int days) {
long backDateMS = System.currentTimeMillis() - ((long)days) *24*60*60*1000;
Date backDate = new Date();
backDate.setTime(backDateMS);
return backDate;
}


The Java Utility method getDateAfterDays() returns a java.util.Date instance with a date after number of days specified.

/**
* This utility method returns a future date after number of days.
* @param days
* @return
*/
public static Date getDateAfterDays(int days) {
long backDateMS = System.currentTimeMillis() + ((long)days) *24*60*60*1000;
Date backDate = new Date();
backDate.setTime(backDateMS);
return backDate;
}    



You can keep these Utility methods as public static methods of a class say DateUtility and call it anywhere in your application using DateUtility.getDateAfterDays() or DateUtility.getDateBeforeDays().

display a future date in java, java date future, java future date

Post a Comment Default Comments

  1. I think it can also be done using Calendar class, I have never tried it though.

    ReplyDelete
  2. You are absolutely right...here is a post on same utility method using Calendar

    ReplyDelete
  3. how to find a future date....
    for an example... from the date "24/4/1994" i want to add 225 days and find the date after that.. how??

    ReplyDelete
  4. how i get the feature date ........?

    i will pass string as "04/50" from this if current year is 2014 then i am expecting 04/2050

    please help me some one

    ReplyDelete
  5. i have a date as "04/50"

    i am expecting if the current year is 2014 then i want the format is like "04/2014"

    please help me some one

    ReplyDelete

Individuals who comment on FromDev at regular basis, will be rewarded in Top Commenter section. (Comments are selectively moderated so please do not spam)

emo-but-icon

...

item