424

I want to convert a java.util.Date object to a String in Java.

The format is 2010-05-30 22:15:52

Vadzim
  • 21,258
  • 10
  • 119
  • 142
novicePrgrmr
  • 16,009
  • 30
  • 76
  • 98
  • 2
    Similar question: http://stackoverflow.com/questions/4772425/format-date-in-java – Vadzim Mar 26 '15 at 16:18
  • @harschware FYI, the [*Joda-Time*](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the [*java.time*](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 16 '18 at 21:29
  • 1
    I recommend you don’t use and `Date` in 2019. That class is poorly designed and long outdated. Instead use `Instant` or another class from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. May 23 '19 at 14:07

18 Answers18

792

Convert a Date to a String using DateFormat#format method:

String pattern = "MM/dd/yyyy HH:mm:ss";

// Create an instance of SimpleDateFormat used for formatting 
// the string representation of date according to the chosen pattern
DateFormat df = new SimpleDateFormat(pattern);

// Get the today date using Calendar object.
Date today = Calendar.getInstance().getTime();        
// Using DateFormat format method we can create a string 
// representation of a date with the defined format.
String todayAsString = df.format(today);

// Print the result!
System.out.println("Today is: " + todayAsString);

From http://www.kodejava.org/examples/86.html

Ali Ben Messaoud
  • 11,042
  • 8
  • 50
  • 80
  • 25
    why use `Calendar` instead of plain `new Date()` ? Is there difference ? – Alexander Malakhov Aug 19 '13 at 04:35
  • 10
    Beware: SimpleDateFormat is not thread safe. http://stackoverflow.com/questions/6840803/simpledateformat-thread-safety – Zags Jan 17 '14 at 00:20
  • 1
    The format in your answer does not match what the OP asked for. Also more complicated than it needs to be. – Lukos Jan 30 '14 at 10:40
  • 24
    Calendar is an abstract class, Date is concrete. Date has no idea about TimeZone, Locale, or any of that good stuff that we all never use. – nckbrz Mar 13 '14 at 22:40
  • 33
    The `MM/dd/yyyy` format is stupid and broken. Do not use it. Always use `dd/MM/yyyy` or `yyyy-MM-dd`. – SystemParadox Sep 23 '15 at 12:53
  • 13
    @SystemParadox - It's stupid, but that doesn't make it pointless. I've been specifically asked to use it because it matches what people expect on reports. (I'd prefer `yyyy-MM-dd` everywhere, but what can you do?). – Autumn Leonard Oct 22 '15 at 21:00
  • 1
    For other formats, see http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – Autumn Leonard Oct 22 '15 at 21:01
  • 2
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 16 '18 at 21:28
236
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
Charlie Salts
  • 12,189
  • 7
  • 43
  • 75
66

Commons-lang DateFormatUtils is full of goodies (if you have commons-lang in your classpath)

//Formats a date/time into a specific pattern
 DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
Kadiri
  • 208
  • 3
  • 8
webpat
  • 1,709
  • 13
  • 17
24

tl;dr

myUtilDate.toInstant()  // Convert `java.util.Date` to `Instant`.
          .atOffset( ZoneOffset.UTC )  // Transform `Instant` to `OffsetDateTime`.
          .format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )  // Generate a String.
          .replace( "T" , " " )  // Put a SPACE in the middle.

2014-11-14 14:05:09

java.time

The modern way is with the java.time classes that now supplant the troublesome old legacy date-time classes.

First convert your java.util.Date to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Conversions to/from java.time are performed by new methods added to the old classes.

Instant instant = myUtilDate.toInstant();

Both your java.util.Date and java.time.Instant are in UTC. If you want to see the date and time as UTC, so be it. Call toString to generate a String in standard ISO 8601 format.

String output = instant.toString();  

2014-11-14T14:05:09Z

For other formats, you need to transform your Instant into the more flexible OffsetDateTime.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );

odt.toString(): 2020-05-01T21:25:35.957Z

See that code run live at IdeOne.com.

To get a String in your desired format, specify a DateTimeFormatter. You could specify a custom format. But I would use one of the predefined formatters (ISO_LOCAL_DATE_TIME), and replace the T in its output with a SPACE.

String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                   .replace( "T" , " " );

2014-11-14 14:05:09

By the way I do not recommend this kind of format where you purposely lose the offset-from-UTC or time zone information. Creates ambiguity as to the meaning of that string’s date-time value.

Also beware of data loss, as any fractional second is being ignored (effectively truncated) in your String’s representation of the date-time value.

To see that same moment through the lens of some particular region’s wall-clock time, apply a ZoneId to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

zdt.toString(): 2014-11-14T14:05:09-05:00[America/Montreal]

To generate a formatted String, do the same as above but replace odt with zdt.

String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                   .replace( "T" , " " );

2014-11-14 14:05:09

If executing this code a very large number of times, you may want to be a bit more efficient and avoid the call to String::replace. Dropping that call also makes your code shorter. If so desired, specify your own formatting pattern in your own DateTimeFormatter object. Cache this instance as a constant or member for reuse.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" );  // Data-loss: Dropping any fractional second.

Apply that formatter by passing the instance.

String output = zdt.format( f );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.

Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
  • Here are code examples of formatting with Java 8 Time API: http://stackoverflow.com/a/43457343/603516 – Vadzim Apr 17 '17 at 18:34
  • this code does not work OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ); odt.toString(): 2014-11-14T14:05:09+00:00 Is there a new Java 8 code to have the same format 2014-11-14T14:05:09+00:00 ? Thank you – Bob Bolden May 01 '20 at 18:43
  • @BobBolden You are correct, `Z` is used instead of `+00:00` by default. I fixed the Answer, thanks. FYI, those mean the same thing: `Z`, pronounced “Zulu” means an offset of zero hours-minutes-seconds, the same as `+00:00`. The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) standard supports both styles. – Basil Bourque May 01 '20 at 21:49
  • @BasilBourque sorry, this is unclear. I have Java 8 and there is no instant.atOffset() at all. Could you please advice what should be the correct code for Java 8 to have exactly the same format 2014-11-14T14:05:09+00:00 without instant.atOffset() ? I'm a bit lost :( – Bob Bolden May 02 '20 at 00:29
  • @BobBolden There is indeed an `atOffset` method on `Instant` class in Java 8. See Javadoc: [`Instant::atOffset`](https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#atOffset-java.time.ZoneOffset-). In Java 8, a call like `Instant.now().atOffset( ZoneOffset.UTC ).toString()` will run. Check your `import` statements. Verify your IDE/project is set to run Java 8 or later rather than an earlier version of Java. See the code run live at IdeOne.com: https://ideone.com/2Vm2O5 – Basil Bourque May 02 '20 at 02:43
22

Altenative one-liners in plain-old java:

String.format("The date: %tY-%tm-%td", date, date, date);

String.format("The date: %1$tY-%1$tm-%1$td", date);

String.format("Time with tz: %tY-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);

String.format("The date and time in ISO format: %tF %<tT", date);

This uses Formatter and relative indexing instead of SimpleDateFormat which is not thread-safe, btw.

Slightly more repetitive but needs just one statement. This may be handy in some cases.

Vadzim
  • 21,258
  • 10
  • 119
  • 142
9

Why don't you use Joda (org.joda.time.DateTime)? It's basically a one-liner.

Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");

// output: 2014-11-14 14:05:09
Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
dbow
  • 579
  • 7
  • 17
  • I suggest passing a DateTimeZone as well, rather than assign the JVM’s current default time zone to the `DateTime` object. `new DateTime( currentDate , DateTimeZone.forID( "America/Montreal" ) )` – Basil Bourque Nov 15 '14 at 00:17
7

It looks like you are looking for SimpleDateFormat.

Format: yyyy-MM-dd kk:mm:ss

pickypg
  • 20,592
  • 4
  • 65
  • 79
  • Does the "kk" do anything special? I think Eric wants it in 24-hour time. – Charlie Salts Apr 16 '11 at 01:03
  • 2
    Yes, the hour in day (1-24), but this is likely not what the OP needs. `HH` (0-23) is more common. – BalusC Apr 16 '11 at 01:04
  • 1
    @Cahrlie Salts kk goes from 1-24, where HH goes from 0-23, and it probably was a bit presumptuous of me to assume he wanted 1-24 @BalusC The DateFormat object both parses and formats. – pickypg Apr 16 '11 at 01:06
  • I don't understand the relevance of your last comment. My comment was to Charlie. – BalusC Apr 16 '11 at 01:10
  • I'm used to .Net formats, where HH is 24-time, and hh is am/pm. Hence the head-scratching. – Charlie Salts Apr 16 '11 at 01:22
  • @BalusC Before it was edited or removed, it was mentioned that my solution did not solve the OP's question. – pickypg Apr 16 '11 at 01:56
5

In single shot ;)

To get the Date

String date = new SimpleDateFormat("yyyy-MM-dd",   Locale.getDefault()).format(new Date());

To get the Time

String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());

To get the date and time

String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());

Happy coding :)

Chanaka Fernando
  • 1,760
  • 13
  • 19
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 04 '18 at 05:37
4
public static String formateDate(String dateString) {
    Date date;
    String formattedDate = "";
    try {
        date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault()).parse(dateString);
        formattedDate = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return formattedDate;
}
4

The easiest way to use it is as following:

currentISODate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss", "2013-04-14T16:11:48.000");

where "yyyy-MM-dd'T'HH:mm:ss" is the format of the reading date

output: Sun Apr 14 16:11:48 EEST 2013

Notes: HH vs hh - HH refers to 24h time format - hh refers to 12h time format

Rami Sharaiyri
  • 468
  • 5
  • 15
4

If you only need the time from the date, you can just use the feature of String.

Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring( 11 , 19 );

This will automatically cut the time part of the String and save it inside the timeString.

4

Here are examples of using new Java 8 Time API to format legacy java.util.Date:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")
        .withZone(ZoneOffset.UTC);
    String utcFormatted = formatter.format(date.toInstant()); 

    ZonedDateTime utcDatetime = date.toInstant().atZone(ZoneOffset.UTC);
    String utcFormatted2 = utcDatetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z"));
    // gives the same as above

    ZonedDateTime localDatetime = date.toInstant().atZone(ZoneId.systemDefault());
    String localFormatted = localDatetime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
    // 2011-12-03T10:15:30+01:00[Europe/Paris]

    String nowFormatted = LocalDateTime.now().toString(); // 2007-12-03T10:15:30.123

It is nice about DateTimeFormatter that it can be efficiently cached as it is thread-safe (unlike SimpleDateFormat).

List of predefined fomatters and pattern notation reference.

Credits:

How to parse/format dates with LocalDateTime? (Java 8)

Java8 java.util.Date conversion to java.time.ZonedDateTime

Format Instant to String

What's the difference between java 8 ZonedDateTime and OffsetDateTime?

Community
  • 1
  • 1
Vadzim
  • 21,258
  • 10
  • 119
  • 142
2

Try this,

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Date
{
    public static void main(String[] args) 
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = "2013-05-14 17:07:21";
        try
        {
           java.util.Date dt = sdf.parse(strDate);         
           System.out.println(sdf.format(dt));
        }
        catch (ParseException pe)
        {
            pe.printStackTrace();
        }
    }
}

Output:

2013-05-14 17:07:21

For more on date and time formatting in java refer links below

Oracle Help Centre

Date time example in java

Shiva
  • 383
  • 1
  • 6
1
public static void main(String[] args) 
{
    Date d = new Date();
    SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
    System.out.println(form.format(d));
    String str = form.format(d); // or if you want to save it in String str
    System.out.println(str); // and print after that
}
marian0
  • 3,264
  • 3
  • 27
  • 35
Artanis
  • 19
  • 1
1

Let's try this

public static void main(String args[]) {

    Calendar cal = GregorianCalendar.getInstance();
    Date today = cal.getTime();
    DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {           
        String str7 = df7.format(today);
        System.out.println("String in yyyy-MM-dd format is: " + str7);          
    } catch (Exception ex) {
      ex.printStackTrace();
    }
}

Or a utility function

public String convertDateToString(Date date, String format) {
    String dateStr = null;
    DateFormat df = new SimpleDateFormat(format);

    try {
        dateStr = df.format(date);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return dateStr;
}

From Convert Date to String in Java

RamenChef
  • 5,533
  • 11
  • 28
  • 39
David Pham
  • 1,295
  • 13
  • 13
1
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String date = "2010-05-30 22:15:52";
    java.util.Date formatedDate = sdf.parse(date); // returns a String when it is parsed
    System.out.println(sdf.format(formatedDate)); // the use of format function returns a String
Dulith De Costa
  • 8,429
  • 1
  • 53
  • 43
1

One Line option

This option gets a easy one-line to write the actual date.

Please, note that this is using Calendar.class and SimpleDateFormat, and then it's not logical to use it under Java8.

yourstringdate =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
  • 1
    FYI, the terribly troublesome date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 23 '19 at 02:58
  • 1
    (1) The answer is wrong (I just got `2019-20-23 09:20:22` — month 20??) (2) I can’t see that the answer provides anything that isn’t already covered in other answers. (3) Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. May 23 '19 at 07:20
  • Yeah.... I did a mistake and forget to correct it. I added it at quickly way, and didn´t remember .. sorry!! and thanks for your comments guys – Alejandro Teixeira Muñoz May 23 '19 at 11:49
  • @OleV.V. Not everybody has access to the Modern Java data and time api...... so ... It´s also valid this answer... – Alejandro Teixeira Muñoz May 23 '19 at 11:50
  • 1
    Thanks for your comment. If you want to provide an answer for Java 5, or for Java 6 and 7 without any external dependency, very fine, that’s welcome, only please make explicit that that is what you are doing. And your answer is still wrong, you will get surprises around New Year. – Ole V.V. May 23 '19 at 12:33
  • Hahahaha, I think I have not a good day. I just wrote it down quickly to complete this page, as I thought mi line was ok, and as I said I corrected it in my code, but not here.... hahhaha Thanks for the point @OleV.V. – Alejandro Teixeira Muñoz May 23 '19 at 12:49
1
Date date = new Date();
String strDate = String.format("%tY-%<tm-%<td %<tH:%<tM:%<tS", date);
jujuBee
  • 494
  • 5
  • 12