Home > Software design >  Java, converting Calendar format to Date(YYYY-MM-DD)
Java, converting Calendar format to Date(YYYY-MM-DD)

Time:02-16

    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

CodePudding user response:

SimpleDateFormat has parsing datefield in specific format.

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");
Date dt =date1.parse(fullDate1);

CodePudding user response:

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());
  • Related