I have a date on String, like this:
String date="25.07.2007";
And I want to divide it to:
String day;
String month;
String year;
What is the best way to do this?
One way to split a string in Java is to use .split("regex") which splits a string according to the pattern provided, returning a String array.
String [] dateParts = date.split(".");
String day = dateParts[0];
String month = dateParts[1];
String year = dateParts[2];
To get current date: You can also change the format of the date by changing the values passed to SimpleDateFormat. Don't forget the imports.
DateFormat dateFormater = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Date date = new Date();
The modern way is to use the Android version of the back-port of the java.time framework built into Java 8 and later.
First, parse the input string into a date-time object. The LocalDate
class represents a date-only value without time-of-day and without time zone.
String input = "25.07.2007";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM.dd.yyyy" );
LocalDate localDate = LocalDate.parse( input , formatter );
Now you can ask the LocalDate
for its values.
int year = localDate.getYear();
int month = localDate.getMonthValue();
int dayOfMonth = localDate.getDayOfMonth();
You can use the handy Month
enum to localize the name of the month.
String monthName = localDate.getMonth().getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With