-3
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(LeaveDate);
    calendar1.add(Calendar.DAY_OF_MONTH, ProcessDate);
    Date fullDate1 = calendar1.getTime();
    SimpleDateFormat date1 = new SimpleDateFormat("yyyy-MM-dd");

Here the output i.e., date1 is string, how to convert it to Date

Dharun
  • 21
  • 2
  • Does this answer your question? [Java string to date conversion](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion) – hc_dev Feb 15 '22 at 13:16
  • 2
    Welcome to SO! Please give an example of your input and wanted output. What is `LeaveDate` and `ProcessDate` ? If you are not familiar with Stackoverflow yet, take the [tour], read [ask] first. What we need is a [example]. – hc_dev Feb 15 '22 at 13:19
  • 2
    `date1` is not a "string", it's `SimpleDateFormat`. Are you confused about how to use a `SimpleDateFormat`? – Sotirios Delimanolis Feb 15 '22 at 13:33
  • How to use SimpleDateFormat, that's easy: don't! Seriously. Use java.time, the modern Java date and time API. – Ole V.V. Feb 17 '22 at 15:56

2 Answers2

2

tl;dr

Reading your code, apparently you want to take the current moment as seen in the current default time zone, adjust to a particular day of month, and then convert to a moment as seen in UTC to be represented by the outmoded class java.util.Date.

java.util.Date          // Legacy class. Replaced by `java.time.Instant`.
.from(                  // New conversion method added to old class, to move between legacy and modern classes.
    ZonedDateTime       // Represents a moment as seen in a particular time zone.
    .now()              // Implicitly applies the JVM’s current default time zone.
    .withDayOfMonth( yourDesiredDayOfMonthGoesHere )  // Adjust to another moment on another date. Returns another `ZonedDateTime` object immutably, rather than altering original.
    .toInstant()        // Adjust from time zone to UTC. Same moment, different wall-clock time.
)                       // Returns an object for the same moment, but as a legacy `Date` object. Avoid using this class if at all possible.

But your title asks for something different. The title asks how to generate text in a ISO 8601 standard format (YYYY-MM-DD) for a Calendar object. Assuming your Calendar object is a GregorianCalendar object, we can cast. Then we can convert to the modern java.time.ZonedDateTime object, extract the date-only java.time.LocalDate object, and generate standard text. The java.time classes use ISO 8601 formats by default when parsing/generating text, so no need for a formatting pattern.

(GregorianCalendar) yourCalendarHere  // Cast from the more general `Calendar` to the more specific `GregorianCalendar`. 
.toZonedDateTime()                    // Convert from legacy class to modern. Same moment in the same time zone. Returns a `java.time.ZonedDateTime` object.
.toLocalDate()                        // Strip away the time zone and the time-of-day, leaving only the date. Returns a `java.time.LocalDate` object.
.toString()                           // Generate text representing the value of that date in standard ISO 8601 format, YYYY-MM-DD. Returns a `String` object.

Tip: Stop using the terribly flawed legacy date-time classes. Use only java.time.

Formatters

Here the output i.e., date1 is string, how to convert it to Date

You seem to misunderstand the classes involved.

Your date1 is a variable declared to be a SimpleDateFormat object. That class is a formatter. As a formatter, its job is to generate text, not hold text nor hold a date. So your variable is misnamed, as it does not hold a date.

Avoid legacy classes

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Never use Date, Calendar, SimpleDateFormat, and such.

java.time

Replace this:

 Calendar calendar1 = Calendar.getInstance();

… with this:

ZonedDateTime zdt = ZonedDateTime.now() ;  // Implicitly uses the JVM’s current default time zone.

I assume that in this code:

calendar1.setTime(LeaveDate);

… the LeaveDate (should have been named with initial lowercase, leaveDate) represents a java.util.Date object. And you are trying to get a calendar object set to the moment represented by that Date object.

In java.time, we use immutable objects. So, no use of set methods. In java.time, if handed a java.util.Date object, immediately convert to an Instant. Both classes represent a moment as seen in UTC, with an offset of zero hours-minutes-seconds. To convert, use the new conversion methods added to the old classes.

Instant instant = leaveDate.toInstant() ;

Adjust that moment into a time zone.

ZoneId z = ZoneId.systemDefault() ; // The JVM’s current default time zone.
ZonedDateTime zdt = instant.atZone( z ) ;

Both instant & zdt represent the same moment, the very same point on the timeline. But their date and time-of-day are adjusted for the wall-clock time used by the people of two different regions. If someone in Iceland, where they use UTC as their time zone, called someone in Tokyo, and both people looked up to see the calendar and clock on their respective walls, they would see a different time and possibly a different date.

In your line:

calendar1.add(Calendar.DAY_OF_MONTH, ProcessDate);

… I am guessing that you want to set the day-of-month while keeping the same month, year, and time-of-day. For example, let's use the 23rd. Notice that we generate a new ZonedDateTime rather than alter ("mutate") the original. Adjustments are made automatically if the result would be impossible, such as the 30th of February.

ZonedDateTime zdtForSpecificDayOfMonth = zdt.withDayOfMonth( 23 ) ;  // Change day-of-month to the 23rd. 

Regarding your line:

Date fullDate1 = calendar1.getTime();

… as I said above, you should avoid using Date in modern Java. But if you must do so to interoperate with old code not yet updated to java.time, extract an Instant from the ZonedDateTime object, and convert to a java.util.Date.

Instant instant = zdtForSpecificDayOfMonth.toInstant() ;  // Adjust from a time zone to an offset of zero hours-minutes-seconds. 
java.util.Date d = Date.from( instant ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
-1

Parsing dates in Java with DateFormat or descendants

Tested with Java's REPL jshell

jshell> import java.text.SimpleDateFormat;
jshell> var df = new SimpleDateFormat("yyyy-MM-dd");
df ==> java.text.SimpleDateFormat@f67a0200
jshell> Date dt =  df.parse("2022-02-15");
dt ==> Tue Feb 15 00:00:00 CET 2022

Read the official JavaDoc for class SimpleDateFormat to figure out how to use it to parse a String to Date:

import java.text.SimpleDateFormat;

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date dt =  df.parse("2022-02-15");
System.out.println(dt); // prints Tue Feb 15 00:00:00 CET 2022

Explained:

  • The "yyyy-MM-dd" as argument to the constructor is a date-format literal (representing ISO-date format).
  • The parse method parses a String with this format and returns the Date object if valid format, or throws a ParseException.

Or search Stackoverflow for [java] String to Date to find similar questions.

Formatting dates in Java with DateFormat or descendants

The other way round you can also format a Date object to have a well-formatted String representation. Use the format method of your DateFormat instance:

import java.text.SimpleDateFormat;

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date dt =  df.parse("2022-02-15");

String formatted = df.format(dt);
System.out.println(formatted);

For example to format your Calendar instance use:

Calendar calendar1 = Calendar.getInstance();

//  whatever modifies the calendar left out here

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formatted = df.format(dt);
System.out.println(calendar1.getTime());
hc_dev
  • 8,389
  • 1
  • 26
  • 38