99

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?

2
  • 2
    A Date object has no format, it is just a number representing the date. The date can be represented by a String with the format of "yyyy-MM-dd". Commented May 19, 2009 at 13:58
  • 1
    You can NOT create a formatted Date object Commented May 11, 2021 at 15:39

10 Answers 10

195

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();
}
Sign up to request clarification or add additional context in comments.

8 Comments

instead of getting string format, can i get output in Date format?
@Rachel: Sure, just use parse and don't go on to format. parse parses a String to a Date.
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 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.
FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 & Java 9. See Tutorial by Oracle.
|
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.

Comments

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);
}

3 Comments

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 dschneller.blogspot.com/2007/04/… :-))
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...
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.
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

Comments

5

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

Comments

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.

Comments

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

Comments

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

7 Comments

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, and its DateTimeFormatter. Also SimpleDateFormat cannot parse 6 decimals on the seconds (microseconds) correctly.
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).
@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
@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
@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.
|
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

Comments

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

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.