Over a million developers have joined DZone.

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

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

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".

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
java ,date and time ,date formatting ,localization

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}