Convert a Date Object to a Java String

DZone 's Guide to

Convert a Date Object to a Java String

This quick tutorial will walk you through how to convert a date object into a string.

· Java Zone ·
Free Resource

In Java, the java.util.Date class represents a date and time. This class has a number of methods to set and retrieve the various parts that make up a date and time (day, month, hour, etc.), but these methods are deprecated, and the recommended way to set a given field is by using another class: java.util.Calendar. This is an abstract class, and is usually instantiated by calling its getInstance() static method, which returns an object initialized with the current date and time:

Calendar cal = Calendar.getInstance();

In the Calendar class, each field is represented by a static class member (for example, Calendar.YEAR, Calendar.DAY_OF_MONTH, etc.), and the set(int field, int value) method can be used to set a value for a given field: for example, the following code snippet sets the year to 2016:

cal.set(Calendar.YEAR, 2016);

Once all relevant date and time fields have been set, a Date object can be created with the getTime() method:

Date dateObject = cal.getTime();

In order to convert a Date object to a Java string (for example, to print it in a human-readable form), the java.text.SimpleDateFormat class can be used; first, this class is instantiated by specifying the format in which the date and time needs to be printed and the locale setting, then its format() method is called, passing it the Date object containing the date and time:

SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss", Locale.ENGLISH);
String dateString = format.format(dateObject);

An example string obtainable with the above instantiation of the SimpleDateFromat class is "2016.07.14 19:58:06".

java ,date and time ,date formatting ,localization

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}