I struggled almost for an entire day trying to access and manipulate dates for my app. If I use date class, many of the methods show warning that they are deprecated. I took the help of simple date format and tried showing month and date. But some how the output was always wrong.
So, if you need to access dates, set a date to current date or to any other particular date and also read dates from a edit text, you should ideally use 3 classes viz Calendar, Date and SimpleDateFormat.
First create a Calendar object and initialize it with current date.
Calendar cal = Calendar.getInstance();
Now to convert this to Date object use getTime() method.
Date someDate = cal.getTime();//this returns a date object.
Now to get a string representation of this date use SimpleDateFormat class
SimpleDateFormat dtFormat = new SimpleDateFormat("dd-MMMM-yyyy");
String dtStr = dtFormat.format(someDate);
For today's date i.e. 22-7-2014, the string dtStr will be 22-July-2014.
Some points to note here
Convert string to date
For this use parse method of SimpleDateFormat
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
try {
Date dt = formatter.parse(datestr);
mCal.setTime(dt);
} catch (ParseException e) {
e.printStackTrace();
}
Setting date or month or year
To set any of date, month, year or even hour, minute and second, you can use this method
calendarObject.set(Calendar.fieldname,value);
e.g.
mCal.set(Calendar.MONTH,5);
mCal.set(Calendar.DAY_OF_MONTH,4);
So, if you need to access dates, set a date to current date or to any other particular date and also read dates from a edit text, you should ideally use 3 classes viz Calendar, Date and SimpleDateFormat.
First create a Calendar object and initialize it with current date.
Calendar cal = Calendar.getInstance();
Now to convert this to Date object use getTime() method.
Date someDate = cal.getTime();//this returns a date object.
Now to get a string representation of this date use SimpleDateFormat class
SimpleDateFormat dtFormat = new SimpleDateFormat("dd-MMMM-yyyy");
String dtStr = dtFormat.format(someDate);
For today's date i.e. 22-7-2014, the string dtStr will be 22-July-2014.
Some points to note here
- In SimpleDateFormat , d - day, M - is month , y is year
- For month don't use lower m. Use M instead. (That mistake caused me hours of struggle).
- If month has 3 or more, it is shown in text, else in number .
- MM - 07
- MMM- Jul
- MMMM-July
Convert string to date
For this use parse method of SimpleDateFormat
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
try {
Date dt = formatter.parse(datestr);
mCal.setTime(dt);
} catch (ParseException e) {
e.printStackTrace();
}
Setting date or month or year
To set any of date, month, year or even hour, minute and second, you can use this method
calendarObject.set(Calendar.fieldname,value);
e.g.
mCal.set(Calendar.MONTH,5);
mCal.set(Calendar.DAY_OF_MONTH,4);
Comments
Post a Comment