tl;dr
LocalDate.now()
.toString()
2016-01-07
Better to always specify your desired/expected time zone explicitly.
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.toString()
Avoid old date-time classes
The java.util.Calendar class you are using is now legacy. Avoid this class, along with java.util.Date and such. These have proven to be poorly designed, confusing, and troublesome.
java.time
The old date-time classes have been supplanted by the java.time framework built into Java 8 and later. Much of the functionality has been back-ported to Java 6 & 7 in the ThreeTen-Backport project, and further adapted to Android in ThreeTenABP.
These modern classes can accomplish your goal in a single line of code, as seen below.
Date-time formatting features
Both the old outmoded date-time classes as well as java.time classes offer formatting features. No need for you to be writing your own formatting code.
Time Zone
Time zone is crucial to determine the date. The date varies around the world by time zone as a new day dawns earlier in the east. This issue was ignored in the Question and other Answers. If omitted, the JVM’s current default time zone is implicitly applied. Better to explicitly specify your desired/expected time zone.
LocalDate
For a date-only value without time-of-day and without time zone, use the LocalDate
. While no time zone is stored within the LocalDate
, a time zone determines “today”.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
ISO 8601
Your desired format of YYYY-MM-DD with double digits happens to comply with the ISO 8601 standard defining sensible formats for textual representations of date-time values. This standard is used by default in java.time classes for parsing/generating strings.
String output = today.toString();
That’s all, 3 lines of code. You could even combine them.
String output = LocalDate.now( ZoneId.of( "America/Montreal" ) ).toString();
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.