How to calculate 30 days back from today using Calendar in Java - java

I want to calculate the date 30 days back from today's date.
public void dateSetup(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd ");
Calendar cal = Calendar.getInstance();
Calendar calReturn = Calendar.getInstance();
jDate_timeOfExpectedReturn1.setText(dateFormat.format(cal.getTime()));
calReturn.add(Calendar.DATE, 30);
jDate_timeOfLoan1.setText(dateFormat.format(calReturn.getTime()));
}
Above you can see that I'm extracting today date using Calendar cal = Calendar.getInstance();
How do I calculate the date of 30 days before the extracted date?
Thanks for any help given.

Just use add() method with -30 days
calReturn.add(Calendar.DATE, -30);

You need to add -30 which will be subtraction.
calReturn.add(Calendar.DATE, -30);

Use a negative number in add() method as -30, which will work like date+(-30) ==> date-30

Related

Creating a custom Date object from Calendar?

I need to create a custom Date object. I get a user input in 24 hr format like hh:mm i.e. 17:49 hrs.
I want to set the hours and minutes as 17 and 49 respectively keeping other details like month , year , day as per the current time.For e.g if today is Dec 16,2014 and the time is 16:00 hrs , then i want a date object as Dec 16,2014 with time as 17:49 hrs. I know i can do this using deprecated apis , however i do not want to use them.I need the date object because i need to pass it to a java timer as java timer does not support any calendar object.
The user input comes as a string and i can parse that string using new SimpleDateFormat(HH:mm) contructor.
I tried using the Calendar.set apis but had no success.
Could some one give some direction on how to proceed.
PS. Sorry , i can't use Joda time :)
EDIT
Since getHours() and getMinutes() are deprecated and have been replaced with Calendar.HOUR_OF_DAY and Calendar.MINUTE respectively, you could use an intermediary calendar object or set the YEAR and DAY to current values.
There is a problem though, if you input next day hour like 24:01 it won't move to the next day. The previous answer, with splitting of string did the overflowing correctly.
public static void main(String[] args) throws ParseException {
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
final String timeInterval = "12:01";
Date date = simpleDateFormat.parse(timeInterval);
final Calendar calendar = Calendar.getInstance(); //calendar object with current date
calendar.setTime(date); //set date with day january 1 1970, this is because you parsed only the time part, the date objects assumes you start from it's lowest value, try a System.out.println(date) before this to see.
calendar.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
calendar.set(Calendar.DATE,Calendar.getInstance().get(Calendar.DATE));
calendar.set(Calendar.MONTH, Calendar.getInstance().get(Calendar.MONTH))
date = calendar.getTime();
System.out.println(date);
}
You can use Calendar to set the time, then extract the date with .getTime() method, which returns a java.util.Date
The idea is to split your string into two parts based on the separator :.
Then simply initialize the calendar and set the hour and minutes with those values.
public static void main(String[] args) throws ParseException {
final String userInput = "17:49";
final String[] timeParts=userInput.split(":");
Calendar cal=Calendar.getInstance(); //current moment calendar
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeParts[0]));
cal.set(Calendar.MINUTE, Integer.parseInt(timeParts[1]));
cal.set(Calendar.SECOND,0); //if you don't care about seconds
final Date myDate=cal.getTime(); //assign the date object you need from calendar
//use myDate object anyway you want ...
System.out.println(myDate);
}
The following code works fine , however i don't want to use any deprecated apis.
...
...
String timeInterval = "18:01";
Date date = simpleDateFormat.parse(timeInterval);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, date.getHours());
calendar.set(Calendar.MINUTE, date.getMinutes());
date = calendar.getTime();
System.out.println(date);
...
...

Changing the date

Basically, I've got a little program that uses date.
Date current = new Date();
current.setDate(current.getDay() + time1);
When I do this it adds to the day, but say time1 = 30 then the month doesn't change when I print the date out. I hope this makes sense I'm kinda new to this.
Use a Calendar to perform date arithmetic and a DateFormat to display the result. Something like,
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 30);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(cal.getTime()));
Use this method
public static Date addDaystoGivenDate(Integer days, Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, days);
return cal.getTime();
}

Error getting month while using Calendar object

I'm using Calendar API to manipulate date. Here is snippet of code i'm trying.
Date date=new SimpleDateFormat("dd/mm/yyyy").parse("05/10/2013");
Calendar cal=Calendar.getInstance();
cal.setTime(date);
int month=cal.get(Calendar.MONTH);
Here i should get month as 9(Oct) but its returning 0(Jan).Even if I change date it still returns 0(Jan).
Why this is happening? Please help me.
use MM instead of mm small m gives Minute in hour and to get Month use capital M
Date date=new SimpleDateFormat("dd/MM/yyyy").parse("05/10/2013");
Calendar cal=Calendar.getInstance();
cal.setTime(date);
int month=cal.get(Calendar.MONTH);
System.out.println("" + month);
Output:
9
Java Docs
sue MM instead of mm in the given date format. M specifies month while m specifies minute according to java doc.
Date date=new SimpleDateFormat("dd/MM/yyyy").parse("05/10/2013")
Calendar cal=Calendar.getInstance();
cal.setTime(date);
int month=cal.get(Calendar.MONTH); // add +1 for correct month(10) otherwise it will be 9

How to set a Java Date object's value to yesterday? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get yesterday's date using Date
What is an elegant way set to a Java Date object's value to yesterday?
With JodaTime
LocalDate today = LocalDate.now();
LocalDate yesterday = today.minus(Period.days(1));
System.out.printf("Today is : %s, Yesterday : %s", today.toString("yyyy-MM-dd"), yesterday.toString("yyyy-MM-dd"));
Do you mean to go back 24 hours in time.
Date date = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000L);
or to go back one day at the time same time (this can be 23 or 25 hours depending on daylight savings)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
These are not exactly the same due to daylight saving.
Convert the Date to a Calendar object and "roll" it back a single day. Something like this helper method take from here:
public static void addDays(Date d, int days)
{
Calendar c = Calendar.getInstance();
c.setTime(d);
c.add(Calendar.DATE, days);
d.setTime(c.getTime().getTime());
}
For your specific case, just pass in days as -1 and you should be done. Just make sure you take into consideration the timezone/locale if doing extensive date specific manipulations.
you can try the follwing code:
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
As many people have already said use Calendar rather than date.
If you find you really want to use dates:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -24);
cal.getTime();//returns a Date object
Calendar cal1 = Calendar.getInstance();
cal1.add(Calendar.DAY_OF_MONTH, -1);
cal1.getTime();//returns a Date object
I hope this helps.
tomred
You can try the following example to set it to previous date.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Today's date is " +dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));

Android Format calendar to output time

I am using the below code to set an alarm. I would like to output what the time for this would be. I don't know if I going about this the wrong way. If I output the variable cal it has a long string of information. How do I extract only the hour and minutes?
Calendar cal = Calendar.getInstance();
// add 5 minutes to the calendar object
cal.add(Calendar.MINUTE, 464);
You can use the static constants as m0skit0 says, or use SimpleDateFormat. Here's some code to show both methods:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 464);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
System.out.println(sdf.format(cal.getTime()));
System.out.println(cal.get(Calendar.HOUR)+":"+cal.get(Calendar.MINUTE));
outputs:
05:31
5:31
Use the get() method on your Calendar object, and use Calendar static constants for the needed field (hour, minute, etc...).
For example:
cal.get(Calendar.Minute);

Categories

Resources