I have a LocalDate variable called date,when I print it displays 1988-05-05 I need to convert this to be printed as 05.May 1988.How to do this?
This question is related to
java
A pretty nice way to do this is to use SimpleDateFormat
I'll show you how:
SimpleDateFormat sdf = new SimpleDateFormat("d MMMM YYYY");
Date d = new Date();
sdf.format(d);
I see that you have the date in a variable:
sdf.format(variable_name);
Cheers.
Could be short as:
LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
With the help of ProgrammersBlock posts I came up with this. My needs were slightly different. I needed to take a string and return it as a LocalDate object. I was handed code that was using the older Calendar and SimpleDateFormat. I wanted to make it a little more current. This is what I came up with.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
void ExampleFormatDate() {
LocalDate formattedDate = null; //Declare LocalDate variable to receive the formatted date.
DateTimeFormatter dateTimeFormatter; //Declare date formatter
String rawDate = "2000-01-01"; //Test string that holds a date to format and parse.
dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;
//formattedDate.parse(String string) wraps the String.format(String string, DateTimeFormatter format) method.
//First, the rawDate string is formatted according to DateTimeFormatter. Second, that formatted string is parsed into
//the LocalDate formattedDate object.
formattedDate = formattedDate.parse(String.format(rawDate, dateTimeFormatter));
}
Hopefully this will help someone, if anyone sees a better way of doing this task please add your input.
System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MMMM yyyy")));
The above answer shows it for today
There is a built-in way to format LocalDate in Joda library
import org.joda.time.LocalDate;
LocalDate localDate = LocalDate.now();
String dateFormat = "MM/dd/yyyy";
localDate.toString(dateFormat);
In case you don't have it already - add this to the build.gradle:
implementation 'joda-time:joda-time:2.9.5'
Happy coding! :)
Source: Stackoverflow.com