How to convert date and time to text in Android

by Goran Siric on Monday, September 26, 2011 12:03 AM

When I was looking how to convert date and time to text in Android, I found method Date.toLocaleString(). This method is deprecated, and we should use DateFormat class.

The most important methods of DateFormat class are getDateTimeInstace(), getDateInstance() and getTimeInstance(). You need to call one of this methods in order to get correct DateTime class instance for converting dates and times to strings.

If you call any of this methods without parameters you will get formater which will convert your date or time to default string format for the user's default locale.

Important:

It is important that you use java.text.DateFormat and not android.text.format.DateFormat, so check your imports if you have any errors.

Some examples

To convert date and time to default format:

Date dt = new Date();
DateFormat formater = DateFormat.getDateTimeInstance();
String formated = formater.format(dt);


To convert date and time to specific format:

Date dt = new Date();
DateFormat formater = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT);
String formated = formater.format(dt);

For more information about DateFormat class see here


android
convert
Date
string
text
Time
Author
Goran Siric

Blog about programming



If you found this useful,
you can buy me a coffe :)

By me a coffe through PayPal :)


Featured articles

Integrating ChatGPT shared links with Sourcetree

We'll guide you through the process of incorporating ChatGPT shared links into your commit messages.

AndEngine - Textures tips and tricks

What you should know abot textures before get started programming your first game.

GIMP script for creating Android icons at once

Script for creating Android icons for different screen resolutions at once. Icons can be saved using standard Android icons naming conventions and saved in appropriate folders.

Creating Android button with image and text using relative layout

Source code with examples how to use relative layout to create nice buttons with text and images in Android

Android application and the Internet

Tutorial about connecting to the web pages on the Internet from Android application, using both POST and GET web requests.