Reputation:
In Java (Android Studio) I have a string that I get from a database (Firebase) like this 20190329
which is a date but I would like to print it out in this format: 29-03-2019
. So, I just need to move 2019
to the end of the string and 29
to the beggining. I know this can be done by using a loop but is there a simpler way to achieve it?
I already have this code that adds the -
and works well:
StringBuilder sb = new StringBuilder(date); //the variable 'date' contains 20190329 or any other date from the database.
sb.insert(2, "-");
sb.insert(5, "-");
sb.insert(8, "-");
Upvotes: 1
Views: 330
Reputation: 404
You can do it by converting your String to Date and then back to String (with your desired format).
Both actions can be achieved with the use of SimpleDateFormat
class.
For example (wrapped code in a Test class to test it of course),
@Test
public void test() throws ParseException {
String date = "20190329";
Date date_ = new SimpleDateFormat("yyyyMMdd").parse(date);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
System.out.println("Formatted Date : " + sdf.format(date_));
}
will eventually print Formatted Date : 29-03-2019
Upvotes: 0
Reputation: 1243
Use str.substring()
Try by doing this. The substring method returns a substring from the begin index to the end one.
String day = data.substring(6,8);
String month = data.substring(4,6);
String year = data.substring(0,4);
String newDate = day + month + year;
StringBuilder sb = new StringBuilder(date); //the variable 'date' contains 20190329 or any other date from the database.
sb.insert(2, "-");
sb.insert(5, "-");
sb.insert(8, "-");
Upvotes: 1
Reputation: 18588
You can and should use java.time
in order to parse and format date objects:
public static void main(String[] args) {
// use a LocalDate and a DateTimeFormatter with a fitting format to parse the String
LocalDate date = LocalDate.parse("20190329", DateTimeFormatter.ofPattern("yyyyMMdd"));
// print it (or return it as String) using a different format
System.out.println(date.format(DateTimeFormatter.ofPattern("dd-MM-yyyy")));
}
Output of this code is
29-03-2019
Most java.time
functionality is back-ported to Java 6 & Java 7 in the ThreeTen-Backport project.
Further adapted for earlier Android (< API Level 26) in ThreeTenABP.
Upvotes: 6