{"id":78,"date":"2014-03-31T05:38:08","date_gmt":"2014-03-31T09:38:08","guid":{"rendered":"https:\/\/cindypotvin.com\/?p=78"},"modified":"2017-02-18T16:36:03","modified_gmt":"2017-02-18T21:36:03","slug":"formatting-dates-with-java-in-android-applications","status":"publish","type":"post","link":"https:\/\/cindypotvin.com\/formatting-dates-with-java-in-android-applications\/","title":{"rendered":"Formatting Dates with Java in Android Applications"},"content":{"rendered":"
To format dates in an Android application, you must keep in mind that dates formatted using the Android SDK take into account the locale, which includes the country and language (this is also called a culture). The locale is configured in the Settings<\/em> application of the device. In general using the locale of the device is the best option, but this may be unacceptable for enterprise applications where all users need to see the same format, regardless of the language of the device. Also, dates that are saved to a file or a database should always have the same format.<\/p>\n Here is a list of the many classes involved in handling and formatting dates :<\/p>\n The java.util.Date<\/em> is a specific point on a timeline : it can check if its date is before or after another date, but it has no idea of how it fits in a month or in a year. The java.util.Calendar<\/em> class is the one that handles how a calendar for a year behaves: for example, you need a Calendar object to get the current date or time, to know when a month start and ends or to check what is the next year. So, to get a java.util.Date<\/em> for the current date, you must get an instance of the java.util.Calendar<\/em>, which is initialised by default at the current date and time.<\/p>\n After that, if you want to display the date retrieved from the calendar, you need to get the date format for the current locale of the device with the android.text.format.DateFomat<\/em> class that returns a java.text.DateFormat<\/em>. For example, to display the current date and time in the current locale, you can use the following code :<\/p>\n Finally, if you need to format a date using a fixed format, you can supply your own format to the java.util.SimpleDateFormat<\/em> class :<\/p>\n\n
Date currentDate = Calendar.getInstance().getTime();<\/pre>\n
Date currentDate = Calendar.getInstance().getTime();\r\njava.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(this);\r\nString formattedCurrentDate = dateFormat.format(currentDate);<\/pre>\n
Date currentDate = Calendar.getInstance().getTime();\r\njava.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat(\"dd\/MM\/yyyy\");\r\nString formattedCurrentDate = simpleDateFormat.format(currentDate);<\/pre>\n