0

This is a java code where it adds the date with time hours and minutes if a possible day to

    timeAddition("06/20/2019;23:30", 60, "m")

    public static String timeAddition(String TimeAndDate, int addTime, String units_M_H) {
        try {
            String returnTime = TimeAndDate;
            final long ONE_MINUTE_IN_MILLIS = 60000;

            DateFormat dateFormat = new SimpleDateFormat("MM/dd/YYYY;HH:mm");
            Date date = dateFormat.parse(TimeAndDate);
            Calendar Cal = Calendar.getInstance();

            Cal.setTime(date);

            if (units_M_H.trim().equalsIgnoreCase("h")) {
                Cal.add(Calendar.HOUR_OF_DAY, addTime);
                returnTime = dateFormat.format(Cal.getTime()).toString();
            } else if (units_M_H.trim().equalsIgnoreCase("m")) {
                long timeInMili = date.getTime();
                date = new Date(timeInMili + (addTime * ONE_MINUTE_IN_MILLIS));
                returnTime = dateFormat.format(date);
            }

            return returnTime;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

The expected output is 06/21/2019;00:30 but the actual output is 12/31/2019;00:30

  • 1
    Change the format to: `"MM/dd/yyyy;HH:mm"` – forpas Jun 20 '19 at 13:01
  • 2
    **Side Note:** The `Date` and `Calendar` classes have long been replaced by the `java.time` classes. You should use [`LocalDate`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) instead. – Zephyr Jun 20 '19 at 13:02
  • 1
    You are using terrible date-time classes that were supplanted years ago by the *java.time* classes defined in JSR 310. – Basil Bourque Jun 20 '19 at 17:25

2 Answers2

2

java.time

Do not reinvent the wheel, Java already has all instruments to do such operations. See the java.time package of classes built into Java. See Tutorial.

String timestamp = "06/20/2019;23:30";
LocalDateTime ldt = LocalDateTime.parse(timestamp,
                         DateTimeFormatter.ofPattern("MM/dd/yyyy;HH:mm"));
System.out.println(ldt);
LocalDateTime ldt2 = ldt.plus(60L, ChronoUnit.MINUTES);
System.out.println(ldt2);

Will print that you expect.

2019-06-20T23:30
2019-06-21T00:30

Hope this helps!

Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
Sergey Prokofiev
  • 1,635
  • 1
  • 11
  • 17
0

Use yyyy for year.

YYYY represents week year.

xingbin
  • 23,890
  • 7
  • 43
  • 79