Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

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

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

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

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}