0

I need to save the current Date + 7 days in iso8601 format as following:

20161107T12:00:00+0000 

Where the part after the "T" is fixed.

I tried the following:

Calendar exDate1 = Calendar.getInstance();
exDate1.add(Calendar.DATE , 7);
Date Date1 = exDate1.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDD");
String Date = sdf.format(Date1 + "T12:00:00+0000");

With no success.

Eng7
  • 632
  • 1
  • 8
  • 25
  • 1
    please check out http://stackoverflow.com/questions/2201925/converting-iso-8601-compliant-string-to-java-util-date – Christoph-Tobias Schenke Nov 07 '16 at 09:02
  • 4
    `String Date = sdf.format(Date1) + "T12:00:00+0000";`. Also, please, follow Java naming conventions - don't use uppercase names for your variables – AJPerez Nov 07 '16 at 09:04

2 Answers2

1

use this 'yyyyMMdd'pattern

    Calendar currentDate = Calendar.getInstance();
    currentDate.add(Calendar.DATE, 7);
    Date date = currentDate.getTime();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    String formattedDate = sdf.format(date).concat("T12:00:00+0000");
Jobin
  • 5,610
  • 5
  • 38
  • 53
1

Another way is using the new java.time-API in Java-8:

String result =
    DateTimeFormatter.BASIC_ISO_DATE.format(
        LocalDate.now(ZoneOffset.UTC).plusDays(7)
    ) + "T12:00:00+0000";
System.out.println(result); // 20161114T12:00:00+0000 

Update due to your choice of timezone offset:

You tried to implicitly use the system timezone to determine the current local time but apply a fixed offset of UTC+0000. This is an inconsistent combination. If you apply such a zero offset then you should also determine the current date according to UTC+0000, not in your system timezone (ZoneId.systemDefault()).

The proposal of editor @Nim

Alternatively - the string above may not have the correct offset:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HH:mm:ssZ");
String date = LocalDate.now().plusDays(7).atTime(12, 0).atZone(ZoneId.systemDefault()).format(formatter);

would yield the result:

20161114T12:00:00+0100

which is probably not what you want. I also try to avoid the expression LocalDate.now() without any arguments because it hides the dependency on the system timezone.

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126