1

I want to calculate 4 months after the date I pulled from the database. How can I do that. The output of history is as follows.

Wed Nov 27 14:42:23 GMT+03:00 2019

  JSONObject form_tarih2 = jObj.getJSONObject("form_tarih2");
        String date = form_tarih2.getString("date");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
        Date calculateDate = sdf.parse(date);
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
berkoberkonew
  • 77
  • 1
  • 8
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Feb 11 '20 at 18:19

1 Answers1

5

Try this:

JSONObject form_tarih2 = jObj.getJSONObject("form_tarih2");
String date = form_tarih2.getString("date");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
Date calculateDate = sdf.parse(date);

final Calendar calendar = Calendar.getInstance();
calendar.setTime(calculateDate);
calendar.add(Calendar.MONTH,4);

You can add/sub days, months, year etc according to your need using Calendar

Harsh Jatinder
  • 833
  • 9
  • 15
  • I/System.out: calendarjava.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=libcore.util.ZoneInfo[id="Europe/Istanbul",mRawOffset=10800000,mEarliestRawOffset=7016000,mUseDst=false,mDstSavings=0,transitions=129],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2020,MONTH=2,WEEK_OF_YEAR=48,WEEK_OF_MONTH=5,DAY_OF_MONTH=27,DAY_OF_YEAR=331,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=2,HOUR_OF_DAY=14,MINUTE=42,SECOND=23,MILLISECOND=0,ZONE_OFFSET=10800000,DST_OFFSET=0] – berkoberkonew Feb 10 '20 at 10:36
  • My answer was based on `java.util.Calendar`. But you can use GregorianCalendar as well, but syntax and implementation might be a bit different for that. – Harsh Jatinder Feb 10 '20 at 10:42
  • are you directly printing `calendar` instance? you have to format date again by calling `sdf.format(calendar.getTimeInMillis());` – Harsh Jatinder Feb 10 '20 at 10:48