Android Date formatter and Time formatter

Date formatter and Time formatter are the ways to convert your date to various date formats, like:
03/01/2015 to 03/01/2015, Tue
03/01/2015 to 03/01/2015, Tuesday
03/01/2015 to 03 Jan, 2015

16:30:00 to 04:30 PM
04:30:00 to 04.30 AM and many more..

SimpleDateFormat class is used to change your format of date and time.

Lets look at example, 
String currentDate = "03/01/2015";
String inPattern = "dd/MM/yyyy";
String outPattern = "dd/MM/yyyy, EEE";
SimpleDateFormat input = new SimpleDateFormat(inPattern);
SimpleDateFormat output = new SimpleDateFormat(outPattern);

Date date = null;

String convertedDate = "";
try {
date = input.parse(currentDate);
convertedDate = output.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
output: convertedDate = 03/01/2015, Tue

Explanation:
  • currentDate is the original date.
  • inPattern in the dateformat of currentDate DateFormat
  • outPattern in the dateformat of your converted date DateFormat
  • input and output is instance of SimpleDateFormat are assigned to their pattern respectively
  • date is instance of Date. Using "input", parse your current date, that will return date object.
  • convertedDate is your output date. Using "output", format your date object, that will return output date in String type.
We can do same for time.
String currentTime = "16:30:00";
SimpleDateFormat HOUR = new SimpleDateFormat("H:mm:ss");
SimpleDateFormat hour = new SimpleDateFormat("hh:mm a");
String convertedTime;
Date dateObj;
try {
dateObj = HOUR.parse(currentTime);
convertedTime = hour.format(dateObj);
} catch (ParseException e) {
e.printStackTrace();
}
output: convertedTime = 04:30 PM

You can find many more date formats at SimpleDateFormat.

Comments

Popular posts from this blog

SQLiteDatabase (Without SqliteOpenHelper class)

Set current date to Button and Datepicker dialog

MVC Architecture in Android