I try to set a simple date certain years after with calendar:
String date is a parameter of this metod.
SimpleDateFormat format = new SimpleDateForm
-
You are using lowercase "m" for month, when you should be using uppercase "M", i.e
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
lowercase "m" is used to format minutes - see the java API for SimpleDateFormat for more details.
讨论(0)
-
You have to use uppercase for month, otherwise you get minutes =)
try:
dd.MM.yyyy
More: http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
讨论(0)
-
Other Answers are correct but outdated.
tl;dr
LocalDate.parse(
"23.01.2017" ,
DateTimeFormatter.ofPattern( "dd.MM.uuuu" )
)
Avoid legacy date-time classes
FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat
are now legacy, supplanted by the java.time classes. See Tutorial by Oracle.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM.uuuu" );
LocalDate localDate = LocalDate.parse( "23.01.2017" , f ); // January 23, 2017.
And going the other direction. Note that unlike the legacy classes, the java.time class have sane month numbering, 1-12 for January-December.
LocalDate localDate = LocalDate.of( 2017 , 1 , 23 ); January 23, 2017.
String output = localDate.format( f );
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.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
- See How to use ThreeTenABP….
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.
讨论(0)
- 热议问题