Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

Date and Time Formatting in Android

In Android, the java.text.SimpleDateFormat class is often used for date and time formatting. However, Android also offers the android.text.format.DateFormat class, which respects the user's preferred date and time format.

Let's walk through some examples using both methods.

1. Using SimpleDateFormat:

import java.text.SimpleDateFormat
import java.util.*

val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
val currentDate = sdf.format(Date())

println(currentDate)  // Example output: "2023-09-10 14:20:55"

In the above code:

  • "yyyy-MM-dd HH:mm:ss" is the format string.
  • Locale.getDefault() ensures the date and time are formatted according to the default locale.

2. Using android.text.format.DateFormat:

This method formats dates and times in a way that's familiar to the user, based on their device's settings.

import android.text.format.DateFormat

val is24HourFormat = DateFormat.is24HourFormat(context)
val userPreferredTime = DateFormat.getTimeFormat(context).format(Date())

println(userPreferredTime)  // The output format will vary based on the user's device settings.

In the above code:

  • DateFormat.is24HourFormat(context) checks if the user prefers a 24-hour format.
  • DateFormat.getTimeFormat(context) gets the time format preferred by the user.

Few Tips:

  1. Always Use Locale with SimpleDateFormat: Always provide a locale when using SimpleDateFormat to prevent potential bugs with date and time representations in different cultures. For instance, Locale.US ensures the date and time format stays consistent, regardless of the device's locale.

  2. User Preference is Key: If displaying a date or time to a user, it's generally best practice to respect their formatting preferences. Use DateFormat for this purpose.

  3. UTC and Time Zones: If working with different time zones, especially in cases of syncing with servers, always consider converting your dates to UTC before storing or transmitting, and then convert back to the local time zone for display. This avoids confusion and ensures consistency.

  4. Java 8 Time API: If your minSdkVersion is 26 or higher, or if you're using a backported version, you can make use of the newer Java 8 Time API (java.time.*), which provides a more comprehensive and consistent set of date-time operations.

  5. Testing: When dealing with date and time operations, always write tests to ensure accuracy and correct behavior, especially if the functionality is critical to your application.

  1. SimpleDateFormat in Android example:

    • Description: SimpleDateFormat is a class in Android that allows you to format and parse dates and times using a specified pattern. It's versatile and widely used for date formatting.
    • Code (Kotlin):
      val currentDate = Date()
      val pattern = "yyyy-MM-dd HH:mm:ss"
      val simpleDateFormat = SimpleDateFormat(pattern, Locale.getDefault())
      val formattedDate = simpleDateFormat.format(currentDate)
      
  2. Customizing date and time formats in Android:

    • Description: You can customize date and time formats using patterns with SimpleDateFormat. Patterns define how the date and time components are formatted.
    • Code (Kotlin):
      val pattern = "EEE, MMM d, yyyy 'at' hh:mm a"
      val simpleDateFormat = SimpleDateFormat(pattern, Locale.getDefault())
      val formattedDate = simpleDateFormat.format(currentDate)
      
  3. Handling time zones in Android date formatting:

    • Description: When working with dates and times, it's important to consider time zones. You can set the time zone for a SimpleDateFormat instance to ensure correct conversions.
    • Code (Kotlin):
      val timeZone = TimeZone.getTimeZone("UTC")
      val simpleDateFormat = SimpleDateFormat(pattern, Locale.getDefault())
      simpleDateFormat.timeZone = timeZone
      val formattedDate = simpleDateFormat.format(currentDate)
      
  4. Formatting relative time in Android:

    • Description: Formatting relative time involves displaying how much time has passed since a certain point. Android provides DateUtils for this purpose.
    • Code (Kotlin):
      val timeAgo = DateUtils.getRelativeTimeSpanString(
          currentDate.time,
          System.currentTimeMillis(),
          DateUtils.MINUTE_IN_MILLIS
      )
      
  5. Date and time pickers in Android with formatting:

    • Description: Android provides date and time pickers for user input. After obtaining the selected date or time, you can format it as needed.
    • Code (Kotlin):
      // Example of using DatePickerDialog
      val datePicker = DatePickerDialog(
          this,
          { _, year, month, dayOfMonth ->
              val selectedDate = Calendar.getInstance()
              selectedDate.set(year, month, dayOfMonth)
              val formattedDate = simpleDateFormat.format(selectedDate.time)
              // Use formattedDate as needed
          },
          year,
          month,
          day
      )
      datePicker.show()
      
  6. Using DateTimeFormatter in Android:

    • Description: DateTimeFormatter is a modern alternative to SimpleDateFormat introduced in Java 8. In Android, you can use java.time.format.DateTimeFormatter for formatting.
    • Code (Kotlin):
      val dateTime = LocalDateTime.now()
      val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
      val formattedDateTime = dateTime.format(formatter)
      
  7. Localization and internationalization for date and time in Android:

    • Description: To support different locales, use resources for date and time formats. Android's resource qualifiers can help with localization.
    • Code (XML - res/values/strings.xml):
      <string name="date_format">MMM dd, yyyy</string>
      
      Code (Kotlin):
      val dateFormat = getString(R.string.date_format)
      val formattedDate = SimpleDateFormat(dateFormat, Locale.getDefault()).format(currentDate)