How To Get Day,month,year From String Date?
Solution 1:
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");
Datedate=newDate();
Solution 2:
java.time
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.
Stringinput="25.07.2007";
DateTimeFormatterformatter= DateTimeFormatter.ofPattern( "MM.dd.yyyy" );
LocalDatelocalDate= LocalDate.parse( input , formatter );
Now you can ask the LocalDate
for its values.
intyear= localDate.getYear();
intmonth= localDate.getMonthValue();
int dayOfMonth = localDate.getDayOfMonth();
You can use the handy Month
enum to localize the name of the month.
StringmonthName= localDate.getMonth().getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );
Solution 3:
Try this...
String dateArr[] = date.split(".");
String day = dateArr[0];
String month = dateArr[1];
String year = dateArr[2];
or
String day= date.substring(0,2);
String month= date.substring(3,5);
String year= date.substring(6,10);
To get the current date...
DatecurrentDate= Calendar.getInstance().getTime();
To get day, month and year from current date..
int day = currentDate.get(Calendar.DAY_OF_MONTH);
int month = currentDate.get(Calendar.MONTH);
int year = currentDate.get(Calendar.YEAR);
Month starts at 0 here...
Solution 4:
date.split(".") will not work
Split methods takes regex as parameter. For regex "." means any character. Instead we have to pass "\\."as parameter.
String [] dateParts = date.split("\\.");
String day = dateParts[0];
String month = dateParts[1];
String year = dateParts[2];
Solution 5:
publicclassDateTest {
/**
* @param args
* @throws ParseException
*/publicstaticvoidmain(String[] args)throws ParseException {
StringstarDate="7/12/1995 12:00:00 AM";
SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("dd/MM/yyyy");
StringnewDateStr= simpleDateFormat.format(simpleDateFormat.parse(starDate));
String str[] = newDateStr.split("/");
Stringmonth= str[1];
Stringyear= str[2];
}
}
Post a Comment for "How To Get Day,month,year From String Date?"