What I\'m trying to do is pass a date into the Calendar so that it will format the date ready for use with another constructor. So that i can make use of it later using the func
Looks like too much work to me.
As a user, I'd rather pass a Date and make the contract clear. Provide a convenience method that converts String to Date:
public class Top {
public static final DateFormat DEFAULT_FORMAT;
static {
DEFAULT_FORMAT = new SimpleDateFormat("yyyy-MMM-dd");
DEFAULT_FORMAT.setLenient(false);
}
public static void main(String [] args) {
}
public static Date convert(String dateStr) throws ParseException {
return DEFAULT_FORMAT.parse(dateStr);
}
public static String convert(Date d) {
return DEFAULT_FORMAT.format(d);
}
}
LocalDate
Apparently you want a date-only value without a day-of-time. For that use the LocalDate
class rather than Calendar
. The Calendar
class was for a date plus a time-of-day. Furthermore, Calendar
is now legacy, supplanted by the java.time classes after having proven to be troublesome, confusing, and flawed.
Simply pass the desired year, month, and day-of-month to a factory method. The month is sanely numbered 1-12 for January-December unlike Calendar
.
LocalDate ld = LocalDate.of( 2012 , 10 , 20 );
Or, pass a constant for month.
LocalDate ld = LocalDate.of( 2012 , Month.OCTOBER , 20 );
The java.time classes tend to use static factory methods rather than constructors with new
.
To generate a string in standard ISO 8601 format, call toString
String output = ld.toString() ;
2012-10-20
For other formats, search Stack Overflow for DateTimeFormatter
. For example:
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
String output = ld.format( f );
20/10/2012
First you don't need to use toString()
method explicitly while printing your instances. It will be called automatically.
Also, you should use SimpleDateFormat to format your Date
to required string format: -
Calendar cal = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
String date = format.format(cal.getTime());
System.out.println(date);
OUTPUT: -
2012/10/20
If you want to print the date represented by a calendar instance, as a string, you should use SimpleDateFormatter to format the date in the required format, as follows:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy");
System.out.println(sdf.format(DateD.getTime());
Assuming DateD
is Calendar
, it is default toString()
implementation. You need to call getTime()
to get the date
out of it.
From the java doc of Calendar#toString()
Return a string representation of this calendar. This method is intended to be used only for debugging purposes, and the format of the returned string may vary between implementations. The returned string may be empty but may not be null.
You can use SimpleDateFormat to convert it to String