0

I got these 2 little functions to get the weekday and the date of today:

public String giveDate() {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
    return sdf.format(cal.getTime()).substring(0,1).toUpperCase() + sdf.format(cal.getTime()).substring(1);
}

public String giveDay() {
    SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
    Date d = new Date();
    String dayOfTheWeek = sdf.format(d);
    return dayOfTheWeek.substring(0,1).toUpperCase() + dayOfTheWeek.substring(1);
}

Is there any addition to my current functions to get the result of the following days?

Example of what I mean:

giveDate(0) and giveDay(0) will result in today. giveDate(1) and giveDay(1) will result in tomorrow etc..

Thanks in advance

Avijit
  • 3,834
  • 4
  • 33
  • 45
iGio90
  • 3,251
  • 7
  • 30
  • 43
  • What should be the output? Did you searched over SO for the solution? – Pankaj Kumar Nov 26 '13 at 05:54
  • Hello, yes i already looked around for a possible solution without success. The output is explained in my question. If i call my 2 functions (giveDay() + " - " + giveDate()) i get Tuesday - Nov 26, 2013... what i need is an addition to get the following days. (giveDay(1) + " - " + giveDate(1)) (or something similar) have to result in Wednesday - Nov 27, 2013 – iGio90 Nov 26 '13 at 05:57
  • Check if this helps: http://stackoverflow.com/questions/20139385/name-of-day-in-string-format-with-days-to-furure/20139582#20139582 For any given day/date, you will have to set your Calendar instance accordingly and retrieve the value as per the new value set. – Harsh Singal Nov 26 '13 at 06:03
  • i guess it can help a bit. let me try to add something to my code... i'll get back to you in 10 mins. thanks meanwhile!! – iGio90 Nov 26 '13 at 06:06

1 Answers1

2

You can use below code

public String getDay(int dayFromToday) {
    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
    Calendar today = new GregorianCalendar(); 
    today.add(Calendar.DAY_OF_MONTH, dayFromToday); 
    return sdf.format(today.getTime()); 
}

Where calling way like

System.out.println(getDay(0));
System.out.println(getDay(1));
System.out.println(getDay(2));
System.out.println(getDay(3));

And output is

Nov 26, 2013
Nov 27, 2013
Nov 28, 2013
Nov 29, 2013

You can get previous day by using this method also. To get previous day pass negative value to this method.

For example

System.out.println(getDay(-3)); // 3 days before today

Output will be

Nov 23, 2013
Pankaj Kumar
  • 81,967
  • 29
  • 167
  • 186