98

I want to convert String to Date in different formats.

For example,

I am getting from user,

String fromDate = "19/05/2009"; // i.e. (dd/MM/yyyy) format

I want to convert this fromDate as a Date object of "yyyy-MM-dd" format

How can I do this?

Community
  • 1
  • 1
Gnaniyar Zubair
  • 8,114
  • 23
  • 61
  • 72

10 Answers10

194

Take a look at SimpleDateFormat. The code goes something like this:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

try {

    String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
    e.printStackTrace();
}
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
  • 1
    instead of getting string format, can i get output in `Date` format? – Rachel Apr 20 '12 at 14:01
  • 4
    @Rachel: Sure, just use `parse` and don't go on to `format`. `parse` parses a String to a Date. – Michael Myers Apr 20 '12 at 14:19
  • 3
    But `parse` gives me in `date format` as `Fri Jan 06 00:01:00 EST 2012` but it need in `2012-01-06` date format – Rachel Apr 20 '12 at 14:23
  • 1
    @Rachel it is because when you call `System.out.println(anyDateObject)` the default toString() method is called which has been said to print in that format e.g. `Fri Jan 06 00:01:00 EST 2012`. You need to override it to suit your needs. – KNU Feb 28 '14 at 07:07
  • @Rachel you must see [toString() for Date Class](http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#toString%28%29) to understanding why it works that way. – KNU Feb 28 '14 at 07:16
  • 3
    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 Mar 26 '18 at 19:22
  • @Rachel You are asking the impossible. As Carlos Heuberger said in a comment to the question, a `Date` hasn’t got a format. As in cannot have. – Ole V.V. Apr 17 '19 at 09:32
  • 1
    input and output is string here but questions says something different – Samir Sep 09 '19 at 11:37
17

tl;dr

LocalDate.parse( 
    "19/05/2009" , 
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) 
)

Details

The other Answers with java.util.Date, java.sql.Date, and SimpleDateFormat are now outdated.

LocalDate

The modern way to do date-time is work with the java.time classes, specifically LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

DateTimeFormatter

To parse, or generate, a String representing a date-time value, use the DateTimeFormatter class.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "19/05/2009" , f );

Do not conflate a date-time object with a String representing its value. A date-time object has no format, while a String does. A date-time object, such as LocalDate, can generate a String to represent its internal value, but the date-time object and the String are separate distinct objects.

You can specify any custom format to generate a String. Or let java.time do the work of automatically localizing.

DateTimeFormatter f = 
    DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
                     .withLocale( Locale.CANADA_FRENCH ) ;
String output = ld.format( f );

Dump to console.

System.out.println( "ld: " + ld + " | output: " + output );

ld: 2009-05-19 | output: mardi 19 mai 2009

See in action in IdeOne.com.


About java.time

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

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

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

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
13

Use the SimpleDateFormat class:

private Date parseDate(String date, String format) throws ParseException
{
    SimpleDateFormat formatter = new SimpleDateFormat(format);
    return formatter.parse(date);
}

Usage:

Date date = parseDate("19/05/2009", "dd/MM/yyyy");

For efficiency, you would want to store your formatters in a hashmap. The hashmap is a static member of your util class.

private static Map<String, SimpleDateFormat> hashFormatters = new HashMap<String, SimpleDateFormat>();

public static Date parseDate(String date, String format) throws ParseException
{
    SimpleDateFormat formatter = hashFormatters.get(format);

    if (formatter == null)
    {
        formatter = new SimpleDateFormat(format);
        hashFormatters.put(format, formatter);
    }

    return formatter.parse(date);
}
Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
Agora
  • 202
  • 1
  • 6
  • 9
    CAVEAT!! The idea is good, but the implementation is not. DateFormats must not be stored statically, because they are not thread-safe! If they are used from more than one thread (and this is always risky with statics). FindBugs contains a detector for this (which I happened to contribute initially, after I got bitten. See http://dschneller.blogspot.com/2007/04/calendar-dateformat-and-multi-threading.html :-)) – Daniel Schneller May 19 '09 at 12:54
  • Your blog entry is an interesting read :-) What if the parseDate-method itself i synchronized? The problem though is that it would probably slow the code down... – Agora May 19 '09 at 13:05
  • 1
    As long as the parseDate method was the only method accessing the map, synchronizing it would work. However this would - as you say - introduce a bottleneck. – Daniel Schneller May 19 '09 at 13:24
8

Convert a string date to java.sql.Date

String fromDate = "19/05/2009";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date dtt = df.parse(fromDate);
java.sql.Date ds = new java.sql.Date(dtt.getTime());
System.out.println(ds);//Mon Jul 05 00:00:00 IST 2010
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Ritesh Kaushik
  • 715
  • 2
  • 13
  • 24
5

Check the javadocs for java.text.SimpleDateFormat It describes everything you need.

bluish
  • 26,356
  • 27
  • 122
  • 180
Matt
  • 2,226
  • 16
  • 18
3

While SimpleDateFormat will indeed work for your needs, additionally you might want to check out Joda Time, which is apparently the basis for the redone Date library in Java 7. While I haven't used it a lot, I've heard nothing but good things about it and if your manipulating dates extensively in your projects it would probably be worth looking into.

Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
James McMahon
  • 48,506
  • 64
  • 207
  • 283
2

Simple way to format a date and convert into string

    Date date= new Date();

    String dateStr=String.format("%td/%tm/%tY", date,date,date);

    System.out.println("Date with format of dd/mm/dd: "+dateStr);

output:Date with format of dd/mm/dd: 21/10/2015

Khalid Habib
  • 1,100
  • 1
  • 16
  • 25
2

Suppose that you have a string like this :

String mDate="2019-09-17T10:56:07.827088"

Now we want to change this String format separate date and time in Java and Kotlin.

JAVA:

we have a method for extract date :

public String getDate() {
    try {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
        Date date = dateFormat.parse(mDate);
        dateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
        return dateFormat.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}

Return is this : 09/17/2019

And we have method for extract time :

public String getTime() {

    try {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
        Date date = dateFormat.parse(mCreatedAt);
        dateFormat = new SimpleDateFormat("h:mm a", Locale.US);
        return dateFormat.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}

Return is this : 10:56 AM

KOTLIN:

we have a function for extract date :

fun getDate(): String? {

    var dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US)
    val date = dateFormat.parse(mDate!!)
    dateFormat = SimpleDateFormat("MM/dd/yyyy", Locale.US)
    return dateFormat.format(date!!)
}

Return is this : 09/17/2019

And we have method for extract time :

fun getTime(): String {

    var dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US)
    val time = dateFormat.parse(mDate!!)
    dateFormat = SimpleDateFormat("h:mm a", Locale.US)
    return dateFormat.format(time!!)
}

Return is this : 10:56 AM

milad salimi
  • 1,580
  • 2
  • 12
  • 31
  • 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`. Also `SimpleDateFormat` cannot parse 6 decimals on the seconds (microseconds) correctly. – Ole V.V. Sep 18 '19 at 11:18
  • When I run your second snippet, I don’t get `10:56 AM` as you say I should, but instead `11:09 AM` (tested on Oracle jdk-11.0.3). – Ole V.V. Sep 18 '19 at 11:22
  • @OleV.V. , If a method be long outdated , it will be deprecate with a line on it as a sign,if a method or class not deprecated we can use it, i dont say it is best way , maybe we have a better way but this way is simple and understandable,if a method or class was old there is no reason that it is troublesome and for use of `DateTimeFormatter` we need to `minsdk 26` or higher then its not good thing – milad salimi Sep 19 '19 at 07:35
  • @OleV.V. But thanks for your comment and about your second comment i can say that i check it many times in two applicaiton and it return `10:56 AM` – milad salimi Sep 19 '19 at 07:37
  • You’re assuming Android, which the question didn’t. java.time has been backported and can be used on lower Andoird API levels than 26. See [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) and [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Sep 19 '19 at 07:38
  • So apparently `SimpleDateFormat` confusingly behaves differently on Android compared to the behaviour on desktop Java. – Ole V.V. Sep 19 '19 at 07:40
  • 1
    @OleV.V. , Ok but i use a library when i have no way or that API(library) be very very better than my code,because when you add a library you add some codes to your project that may not be used and this is overload for your project,this is my approach and your approach is respectable for me. – milad salimi Sep 19 '19 at 08:41
1

A Date object has no format, it is a representation. The date can be presented by a String with the format you like.

E.g. "yyyy-MM-dd", "yy-MMM-dd", "dd-MMM-yy" and etc.

To acheive this you can get the use of the SimpleDateFormat

Try this,

        String inputString = "19/05/2009"; // i.e. (dd/MM/yyyy) format

        SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy"); 
        SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date dateFromUser = fromUser.parse(inputString); // Parse it to the exisitng date pattern and return Date type
            String dateMyFormat = myFormat.format(dateFromUser); // format it to the date pattern you prefer
            System.out.println(dateMyFormat); // outputs : 2009-05-19

        } catch (ParseException e) {
            e.printStackTrace();
        }

This outputs : 2009-05-19

Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
0

There are multiple ways to do it, but a very practical one is the use String.format which you can use with java.util.Date or java.util.Calendar or event java.time.LocalDate.

String.format is backed by java.util.Formatter.

I like the omnivore take on it.

class Playground {
    public static void main(String[ ] args) {
        String formatString = "Created on %1$td/%1$tm/%1$tY%n";
        System.out.println(String.format(formatString, new java.util.Date()));
        System.out.println(String.format(formatString, java.util.Calendar.getInstance()));
        System.out.println(String.format(formatString, java.time.LocalDate.now()));
    }
}

The output will be in all cases:

Created on 04/12/2022

Created on 04/12/2022

Created on 04/12/2022
gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
  • That can be useful sometimes, but aren’t you answering a different question? If I understood the OP correctly, they wanted an old-fashioned `Date` object as result. – Ole V.V. Dec 04 '22 at 16:52
  • @OleV.V. My answer includes the `java.util.Date` object (see above). It is true that I have included some other date types to underline the usefulness of the method and that might be outside of the scope of the question, but in the bigger picture can be useful to know for developers. – gil.fernandes Dec 04 '22 at 16:58
  • I certainly agree that today we should prefer using the modern `LocalDate` over the poorly designed `Date` and `Calendar` classes, so thanks for including that one. – Ole V.V. Dec 04 '22 at 17:02