Android Date Example/Tutorial

In this post, I will tell you how to do date formatting in Android.

So, Let’s Start:-

1.Date and time come with different formats in different regions in the United States, we often format our dates like this: April 6th, 1981, or 04/06/1981 whereas in Europe, the day normally precedes the month, like this: 6 April 1981, or 06/04/1981. Similarly, some countries have the concept of AM and PM with a 12-hour, whereas others simply use a 24-hour clock.

Let’s talk about basics of Date and Time

1.Date– Date refers to a point in a time.

2.DateTime- refers to some time at the particular date.

3.DateFormat- it is a class used to format date which is readable by human.

getting date from Date class

Date currentdate=new Date();
DateFormat dateformat=DateFormat.getDateTimeInstance();
String date=dateformat.format(currentdate);

Output

androidworkingwithdate

getting date from Calender Instance

Calendar calendar=Calendar.getInstance();
 int year = calendar.get(Calendar.YEAR);
 int month = calendar.get(Calendar.MONTH);
 int day = calendar.get(Calendar.DATE);
 Date todaydate=calendar.getTime();
 DateFormat dateformat=DateFormat.getDateTimeInstance();
 String caldate=dateformat.format(todaydate);

Output

androidworkingwithdate

formatting date according to a certain format

Calendar calendar=Calendar.getInstance();
Date todaydate=calendar.getTime();
DateFormat formatter=new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
String simpledate=formatter.format(todaydate);

Output

androidhowtousedate

formatting date according to given format

long time=System.currentTimeMillis();
Date logtime=new Date(time);
DateFormat formatter1=new SimpleDateFormat("MM/dd/yyyy");
String timelong=formatter1.format(logtime);

Output

androidworkingwithdateformat

getting previous date and year from Calender

Calendar cal = Calendar.getInstance();
Date today = cal.getTime();
//5 days ago's date
Date 2daysAgo = cal.add(Calendar.DATE, -5).getTime();
//4 years ago
cal.add(Calendar.YEAR, -4);