Changing String date format
Solution 1:
The first thing you need to do is parse the original value to a Date
object
String startTime = "08/11/2008 00:00";
// This could be MM/dd/yyyy, you original value is ambiguous
SimpleDateFormat input = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date dateValue = input.parse(startTime);
Once you have that done, you can format the dateValue
any way you want...
SimpleDateFormat output = new SimpleDateFormat("yyyy/MM/dd HH:mm");
System.out.println("" + output.format(dateValue) + " real date " + startTime);
which outputs:
2008/11/08 00:00 real date 08/11/2008 00:00
The reason you're getting 0014/05/01 00:00
is SimpleDateFormat
(when using yyyy/MM/dd HH:mm
) is using 08
for the year, 11
for the month and 2008
for the day, it's doing an internal rolling of the values to correct the values to a valid date
Solution 2:
I should like to contribute the modern answer.
DateTimeFormatter currentFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm");
DateTimeFormatter convertedOutputFormatter = DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm");
String startTime = "08/11/2008 00:00";
LocalDateTime starting = LocalDateTime.parse(startTime, currentFormatter);
System.out.println(starting.format(convertedOutputFormatter));
This prints
2008/11/08 00:00
The SimpleDateFormat
class you tried to use is long outdated and notoriously troublesome. You have experienced but a little of the trouble with it. Instead I am using and recommending java.time
, the modern Java date and time API.
As others have said, you need to use two formatters, one for specifying your current format and one for specifying the desired format.
What went wrong in your code?
Your formatter with format pattern yyyy/MM/dd HH:mm
interpreted 08/11/2008 as the 2008th day of the 11th month of year 8 of the common era. It doesn’t disturb a SimpleDateFormat
with default settings that there are only 30 days in November, it just continues counting into the following months and years, ending up on a date five and a half years later (2008 divided by 365.25 is very close to 5.5).
Question: Can I use java.time
with my Java version?
If using at least Java 6, you can.
- In Java 8 and later the new API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
- On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package
org.threeten.bp
and subpackages.
Links
-
Oracle tutorial: Date Time, explaining how to use
java.time
. - ThreeTen Backport project
- ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
- Java Specification Request (JSR) 310.