SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS");
Date date = new Date();
How Do I make this Java 7 compatible? What changes should I do?
String part = date.getYear() "" String.format("d", date.getMonthValue()) ""
String.format("d", date.getDayOfMonth()) "" String.format("d", date.getHour()) ""
String.format("d", date.getMinute()) "" String.format("d", date.getSecond());
CodePudding user response:
The terrible Date
, Calendar
, and SimpleDateFormat
classes were supplanted by the modern java.time classes defined in JSR 310 and built into Java 8 .
For Java 6 and 7, add the back-port of java.time to your project, the ThreeTen-Backport library. The API is nearly identical to *java.time, so later upgrading your project to modern Java will involve little more than changing the import
statements.
As you may know, Java 6 and 7 are years past their end-of-life. I suggest you consider migrating to Java 8, 11, or 17, if at all possible.
CodePudding user response:
Use a SimpleDateFormat
if upgrading Java (from version 7) is not possible and to avoid any external library:
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
String part = dateFormat.format(date);
Pattern can be changes as needed: see documentation of the SimpleDateFormat
class.
As already advised in this answer, upgrade to a newer Java and then use the classes from java.time
package and sub-packages (like DateTimeFormatter
).