How add 30 days in current date? [duplicate] - java

This question already has answers here:
Is SimpleDateFormat in Java work incorrect or I did any mistake? See code sample [duplicate]
(2 answers)
Parsing a string to date format in java defaults date to 1 and month to January
(2 answers)
Closed 3 years ago.
I want to add 30 days in my current date I searched a lot but did not get the proper solution.
my code
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd");
Calendar c1 = Calendar.getInstance();
String currentdate = df.format(date);
try {
c1.setTime(df.parse(currentdate));
c1.add(Calendar.DATE, 30);
df = new SimpleDateFormat("yyyy-MM-dd");
Date resultdate = new Date(c1.getTimeInMillis());
String dueudate = df.format(resultdate);
Toast.makeText(this, dueudate, Toast.LENGTH_SHORT).show();
} catch (ParseException e) {
e.printStackTrace();
}
The output of this code is :
2019-01-29
I don't why it is showing this output can anyone help me.

You need to use
c1.add(Calendar.DAY_OF_YEAR, 30);
instead of
c1.add(Calendar.DATE, 30);
Try this
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd");
Calendar c1 = Calendar.getInstance();
String currentDate = df.format(date);// get current date here
// now add 30 day in Calendar instance
c1.add(Calendar.DAY_OF_YEAR, 30);
df = new SimpleDateFormat("yyyy-MM-dd");
Date resultDate = c1.getTime();
String dueDate = df.format(resultDate);
// print the result
Utils.printLog("DATE_DATE :-> "+currentDate);
Utils.printLog("DUE_DATE :-> "+dueDate);
OUTPUT
2019-06-04 14:43:02.438 E/XXX_XXXX: DATE_DATE :-> 2019-06-04
2019-06-04 14:43:02.438 E/XXX_XXXX: DUE_DATE :-> 2019-07-04

Another easier option, if on Java 8, use the java.time package which provides functions to perform plus/minus on current date of any units of time, example:
import java.time.LocalDate;
LocalDate date = LocalDate.now().plusDays(30);
//or
LocalDate date = LocalDate.now().plus(30, ChronoUnit.DAYS);

Calendar.getInstance() gives you the current time. You don't need to create another Date object for that.
Calendar current = Calendar.getInstance();
current.add(Calendar.DATE, 30);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date resultdate = new Date(current.getTimeInMillis());
String dueudate = df.format(resultdate);
System.out.println("" + dueudate);

1)Go from date to millis.
2)Create a long variable with value 30L * 24L * 60L * 60L * 1000L.
3)Add this value to the millis you got in step 1
4) Go from this sum back to date again.
Edit: Variables that store millis should be long, not int.
Edit2: Adding "L" besides each number guarantees we won't get an overflow.

Related

How to do subtraction from a particular date using Java [duplicate]

This question already has answers here:
Calendar date to yyyy-MM-dd format in java
(11 answers)
Closed 4 years ago.
I am encountering an issue which is related to Java Date Function.
I'm getting the date from Application (example: 6/5/18) which is in MM/DD/YY format. Now I need to do -2 from the date. I know how to do -2 from current system date using calendar object (see the below code).
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
info("Date is displayed as : "+ PastDate );
I'm not able to put the date which I'm getting from Application in this format. Can someone please help me? (Any other way to do it would also be fine)
I suggest you to use Java 8 compatible Date and Time types.
If you use java.time.LocalDate then this is the solution:
LocalDate.now().minusDays(2)
From your question, it seems that you have the challenge in dealing with formatting, and then doing the subtraction.
I would recommend Java Date and Time Apis for this purpose, using a formatter.
A junit method to achieve your requirement is given below
#Test
public void testDateFormatUsingJava8() {
CharSequence inputdateTxt = "6/5/18";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yy");
LocalDate inputDate = LocalDate.parse(inputdateTxt, formatter);
System.out.println(inputDate.minusDays(2L).format(formatter));
}
#Test
public void testDateCalenderUsingStringSplit() {
String inputdateTxt = "6/5/18";
String[] dateComponenets = inputdateTxt.split("//");
Calendar cal = Calendar.getInstance();
//Know where are the year month and date are stored.
cal.set(Integer.parseInt(dateComponenets[2]), Integer.parseInt(dateComponenets[0]), Integer.parseInt(dateComponenets[2]) );
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
}
#Test
public void testDateCalenderUsingJavaUtilDateApi() throws ParseException {
String inputdateTxt = "6/5/18";
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
Date date = dateFormat.parse(inputdateTxt);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE,-2);
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
The reason why I use "M/d/yy" is because your question does not pad the date and month fields in the input date with a zero. If there is a guarantee that you receive a padded value in the date and month field, using "MM/dd/yy" is suggested.
See the following answer for your reference :
DateTimeFormatterSupport for Single Digit Values
EDIT: considering the limitation to not use Java 8 Date Time APIs, I have added two other alternatives to solve the problem. The OP is free to choose any one of the solutions. Kept the Java 8 solution intact for information purposes.
Calendar cal = Calendar.getInstance();
cal.set(2018, 5, 6); // add this, setting data from the value you parsed
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ PastDate);

Creating date using integers and displaying in a textbox [duplicate]

This question already has answers here:
Convert linux timestamp to android date
(4 answers)
Closed 5 years ago.
I am new to Android Studio and have ran into a problem - I am trying to carry out a calculation whereby I need the current date and time in an integer format. I also need the current date and time to then display in a TextBox.
I have declared the date as an integer as follows:
public static int date1 = (int) (new Date().getTime()/1000);
datedisplay = (TextView) findViewById(R.id.date);
Then I have tried to get the current date and time displayed in a textbox, but it isn't displaying. I was just wondering would anyone know why?
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm");
System.out.println(new Date(new Date(date1).getTime()));
datedisplay.setText(dateFormat.format(date1));
Thank you in advance
Use it in any datatype you want either String or Integer.
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date.getTime());
datedisplay.setText(timeStamp);
new Date().getTime() ; return long value if you diving it by 1000
to convert long to int
better if you use long:
long date1 = new Date().getTime() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm");
Date dt = new Date(date1);
datedisplay.setText(dateFormat.format(dt));
You can also use Calendar class:
Calendar myCalendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm",Locale.getDefault());
String dateString = sdf.format(myCalendar.getTime());
then
datedisplay.setText(dateString);
If you really want to use a int to store your date representation, just use the number of day since the epoch instead of the number of seconds
new Date().getTime()
/1000 //second
/60 //minute
/60 //hour
/24; //day
This will give you a value that will fit in a int for quite some time.
But of course you won't be able to get back the exact precision, if you want the Time part of the Date, you won't be able to. This only allows you to get the Date like yyyy-MM-dd
private static final long EPOCH_DAY = 1000L * 60 * 60 * 24;
public static void main(String[] args){
int i = (int) (new Date().getTime()/EPOCH_DAY);
System.out.println(new Date(i * EPOCH_DAY));
}
Fri Nov 03 01:00:00 CET 2017
(the hours is because of my local being in GMT+1)

convert milliseconds to date [duplicate]

This question already has answers here:
How to convert currentTimeMillis to a date in Java?
(13 answers)
Closed 8 years ago.
Server sending me time as 1390361405210+0530 so if I want to convert this in to date then should I have to add 0530 into 1390361405210 and then calculate date and time?
Any suggestion should be appreciated.Thanks
How about this.
long currentDateTime = 1390361405210L;
Date currentDate = new Date(currentDateTime);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss Z");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+530"));
System.out.println(sdf.format(currentDate));
public static void main( String[] args )
{
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
long milliSeconds=1390361405210L;
Date date = new Date(milliSeconds);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
System.out.println(formatter.format(calendar.getTime()));
System.out.println(formatter.format(date));
}
If we consider that the first part of the String is the number of milliseconds since the epoch, and the second part is a timezone indication (in that case, IST, Indian Standard Time), you can get a readable date like this :
final String jsonDate = "1390361405210+0530";
final Date date = new Date(Long.parseLong(jsonDate.substring(0, jsonDate.length() - 5)));
final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.FULL, Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT" + jsonDate.substring(jsonDate.length() - 5)));
System.out.println(format.format(date));
Output:
January 22, 2014 9:00:05 AM GMT+05:30

YYYY-MM-DD minus 1 day [duplicate]

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 9 years ago.
I have a date variable in the YYYY-MM-DD format.
How can I change the date value to the previous day? So if the value of the variable was 2014-01-01 it would change to 2014-12-31.
You can use a DateFormat and a Calendar, like so
String fmt = "yyyy-MM-dd";
String dt = "2014-01-01";
java.text.DateFormat df = new java.text.SimpleDateFormat(fmt);
java.util.Calendar cal = java.util.Calendar.getInstance();
try {
cal.setTime(df.parse(dt));
cal.add(java.util.Calendar.DAY_OF_MONTH, -1);
System.out.println(cal.getTime());
} catch (Exception e) {
}
Which outputs
Tue Dec 31 00:00:00 EST 2013
Java can parse a date, then subtract one day and output the toString()
documentation: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Date.html
Long version:
String example = "2014-01-01";
DateFormat df = new SimpleDateFormat("YYY-MM-dd", Locale.ENGLISH);
Date result = df.parse(target);
Calendar cal = Calendar.getInstance();
cal.setTime(result);
cal.add(Calendar.DATE, -1);
result = cal.getTime();
System.out.println(df.format(result));

How to subtract X day from a Date object in Java?

I want to do something like:
Date date = new Date(); // current date
date = date - 300; // substract 300 days from current date and I want to use this "date"
How to do it?
Java 8 and later
With Java 8's date time API change, Use LocalDate
LocalDate date = LocalDate.now().minusDays(300);
Similarly you can have
LocalDate date = someLocalDateInstance.minusDays(300);
Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
Java 7 and earlier
Use Calendar's add() method
Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();
#JigarJoshi it's the good answer, and of course also #Tim recommendation to use .joda-time.
I only want to add more possibilities to subtract days from a java.util.Date.
Apache-commons
One possibility is to use apache-commons-lang. You can do it using DateUtils as follows:
Date dateBefore30Days = DateUtils.addDays(new Date(),-30);
Of course add the commons-lang dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang it's a good choice. There is also convenient methods to addYears,addMonths,addWeeks and so on, take a look at the api here.
Java 8
Another possibility is to take advantage of new LocalDate from Java 8 using minusDays(long days) method:
LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);
Simply use this to get date before 300 days, replace 300 with your days:
Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();
Here,
DateTime is org.joda.time.DateTime;
Date is java.util.Date
Java 8 Time API:
Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);
As you can see HERE there is a lot of manipulation you can do. Here an example showing what you could do!
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
//Add one day to current date.
cal.add(Calendar.DATE, 1);
System.out.println(dateFormat.format(cal.getTime()));
//Substract one day to current date.
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
/* Can be Calendar.DATE or
* Calendar.MONTH, Calendar.YEAR, Calendar.HOUR, Calendar.SECOND
*/
With Java 8 it's really simple now:
LocalDate date = LocalDate.now().minusDays(300);
A great guide to the new api can be found here.
In Java 8 you can do this:
Instant inst = Instant.parse("2018-12-30T19:34:50.63Z");
// subtract 10 Days to Instant
Instant value = inst.minus(Period.ofDays(10));
// print result
System.out.println("Instant after subtracting Days: " + value);
I have created a function to make the task easier.
For 7 days after dateString: dateCalculate(dateString,"yyyy-MM-dd",7);
To get 7 days upto dateString: dateCalculate(dateString,"yyyy-MM-dd",-7);
public static String dateCalculate(String dateString, String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
try {
cal.setTime(s.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
cal.add(Calendar.DATE, days);
return s.format(cal.getTime());
}
You may also be able to use the Duration class. E.g.
Date currentDate = new Date();
Date oneDayFromCurrentDate = new Date(currentDate.getTime() - Duration.ofDays(1).toMillis());
You can easily subtract with calendar with SimpleDateFormat
public static String subtractDate(String time,int subtractDay) throws ParseException {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
cal.setTime(sdf.parse(time));
cal.add(Calendar.DATE,-subtractDay);
String wantedDate = sdf.format(cal.getTime());
Log.d("tag",wantedDate);
return wantedDate;
}

Categories