57

I have the following scenario :

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.parse("31/05/2011"));

gives an output

Tue May 31 00:00:00 SGT 2011

but I want the output to be

31/05/2011 

I need to use parse here because the dates need to be sorted as Dates and not as String.

Any ideas ??

MByD
  • 135,866
  • 28
  • 264
  • 277
bhavya
  • 719
  • 2
  • 8
  • 7
  • 8
    Can we add Wiki/FAQ entry or article for date parsing/formatting and timezones? Looks like 1 out of 5 Java questions are about this topic... – Tomasz Nurkiewicz Jun 07 '11 at 08:28
  • 2
    For latecomers: don’t use `Date` and certainly don’t use `SimpleDateFormat`. Use `LocalDate` and `DateTimeFormatter` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). For everyone: You are asking the impossible. A `Date` doesn’t have a format, and you cannot change how its `toString` method works (the same goes for the modern `LocalDate`).. – Ole V.V. Feb 12 '19 at 10:06
  • For a modern solution using *java.time*, see the Answers [by Ole V.V.](https://stackoverflow.com/a/54649203/642706) and [by Avinash](https://stackoverflow.com/a/76841385/642706). – Basil Bourque Aug 05 '23 at 15:22

12 Answers12

73

How about:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));

> 31/05/2011
Naman
  • 27,789
  • 26
  • 218
  • 353
Luciano Fiandesio
  • 10,037
  • 10
  • 48
  • 56
  • 9
    I don't know why this answer is aaccepted. but it does not give the formatted date of type java.uti.Date. format () method returns String. – Radhakrishna Sharma Gorenta Jun 30 '16 at 11:08
  • 3
    @RadhakrishnaGorenta, I'm not sure what you mean by that. There is no such thing "a formatted date of type java.uti.Date". Dates do not have "formats" until they are output on the screen or otherwise serialized. They are just objects. – DavidS Jul 04 '16 at 17:58
  • How does this solve the question of "converting a `util.Date` to `sql.Date` object? – q.Then Nov 22 '16 at 00:34
  • 2
    @Ephemeral which question are you talking about? There is no reference whatsoever to sql.Date... – Luciano Fiandesio Nov 24 '16 at 10:15
55

You need to go through SimpleDateFormat.format in order to format the date as a string.

Here's an example that goes from String -> Date -> String.

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("31/05/2011");

System.out.println(dateFormat.format(date));   // prints 31/05/2011
//                            ^^^^^^
Roalt
  • 8,330
  • 7
  • 41
  • 53
aioobe
  • 413,195
  • 112
  • 811
  • 826
17

Use the SimpleDateFormat.format

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);
BadSkillz
  • 1,993
  • 19
  • 37
6

You can use simple date format in Java using the code below

SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = new Date();
String expectedDate= simpledatafo.format(newDate);
Colin O'Dell
  • 8,386
  • 8
  • 38
  • 75
Shan Abeywicrema
  • 65
  • 1
  • 2
  • 6
4

It makes no sense, but:

System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")))

SimpleDateFormat.parse() = // parse Date from String
SimpleDateFormat.format() = // format Date into String
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
bugs_
  • 3,544
  • 4
  • 34
  • 39
3

If you want to simply output a date, just use the following:

System.out.printf("Date: %1$te/%1$tm/%1$tY at %1$tH:%1$tM:%1$tS%n", new Date());

As seen here. Or if you want to get the value into a String (for SQL building, for example) you can use:

String formattedDate = String.format("%1$te/%1$tm/%1$tY", new Date());

You can also customize your output by following the Java API on Date/Time conversions.

Thiago
  • 883
  • 11
  • 20
3

java.time

Here’s the modern answer.

    DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
    DateTimeFormatter displayFormatter = DateTimeFormatter
            .ofLocalizedDate(FormatStyle.SHORT)
            .withLocale(Locale.forLanguageTag("zh-SG"));

    String dateString = "31/05/2011";
    LocalDate date = LocalDate.parse(dateString, sourceFormatter);
    System.out.println(date.format(displayFormatter));

Output from this snippet is:

31/05/11

See if you can live with the 2-digit year. Or use FormatStyle.MEDIUM to obtain 2011年5月31日. I recommend you use Java’s built-in date and time formats when you can. It’s easier and lends itself very well to internationalization.

If you need the exact format you gave, just use the source formatter as display formatter too:

    System.out.println(date.format(sourceFormatter));

31/05/2011

I recommend you don’t use SimpleDateFormat. It’s notoriously troublesome and long outdated. Instead I use java.time, the modern Java date and time API.

To obtain a specific format you need to format the parsed date back into a string. Netiher an old-fashioned Date nor a modern LocalDatecan have a format in it.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
2

java.time

The question and the answers written at that time use java.util Date-Time API and their formatting API, SimpleDateFormat which was the right thing to do at that time. Java 8, released in March 2014, brought the modern date-time API. It is recommended to stop using the legacy date-time API entirely and switch to the modern Date-Time API.

Also, quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Your problem

You are trying to parse the date string into a java.util.Date object and print it. A java.util.Date object represents only the number of milliseconds since January 1, 1970, 00:00:00 GMT. When you print its object, the string returned by Date#toString, which applies your system's timezone, is printed. Note that a date-time object holds only date-time information, not a format. A format is represented using a string you obtain by formatting the date-time object using a date-time formatting class with the desired pattern.

Modern Date-Time API

The following table shows an overview of different types available in the modern Date-Time API.

enter image description here

The type, LocalDate fits your requirement. You can use different patterns for parsing and formatting using a DateTimeFormatter. The following example uses the same pattern for parsing and formatting:

public class Main {
    public static void main(String[] args) {
        String strDate = "31/05/2011";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ENGLISH);
        LocalDate date = LocalDate.parse(strDate, dtf);
        System.out.printf("Default format: %s, Custom format: %s%n", date, date.format(dtf));
    }
}

Output:

Default format: 2011-05-31, Custom format: 31/05/2011

ONLINE DEMO

Note: Here, you can use y instead of u but I prefer u to y. Also, never use DateTimeFormatter for custom formats without a Locale.

Learn more about the modern Date-Time API from Trail: Date Time.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

You already has this (that's what you entered) parse will parse a date into a giving format and print the full date object (toString).

MByD
  • 135,866
  • 28
  • 264
  • 277
0

I had something like this, my suggestion would be to use java for things like this, don't put in boilerplate code

BasicImplementation

somshivam
  • 759
  • 7
  • 19
0

This will help you. DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); print (df.format(new Date());

Sanjay Jain
  • 3,518
  • 8
  • 59
  • 93
0

This looks more compact. Finishes in a single line.

import org.apache.commons.lang3.time.DateFormatUtils;

System.out.println(DateFormatUtils.format(newDate, "yyyy-MM-dd HH:mm:ss"));
Shiva kumar
  • 673
  • 8
  • 23