13

Hi i want to convert the current date to this format YYYY-MM-DD. However, it will convert the date into String format, but i want to convert it back into Date format. So can anyone advise on this?

This is my code so far

 DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
 Date date = new Date();
 String datestring = dateFormat.format(date); 
atish shimpi
  • 4,873
  • 2
  • 32
  • 50
ayampenyet
  • 241
  • 1
  • 2
  • 15
  • May be this helps [Java string to date conversion][1] [1]: http://stackoverflow.com/questions/4216745/java-string-to-date-conversion – Bharath R Oct 21 '13 at 10:49
  • 2
    Date object has no format, only the string representation of it has the format. – Dhana Krishnasamy Oct 21 '13 at 10:50
  • 3
    IMO, Dates should be always stored as Dates and parsing your own Date isn't a good habit. Date formats should be used for user interaction, not for storing the data itself. And if you want to somehow programatically convert the Date to String, using serialization is much more convenient. – Danstahr Oct 21 '13 at 10:51
  • 1
    FYI: This Question uses troublesome old date-time classes that are now legacy, supplanted by the modern java.time classes. – Basil Bourque Nov 07 '17 at 14:27

5 Answers5

26

try this:

 String DATE_FORMAT_NOW = "yyyy-MM-dd";
 Date date = new Date();
 SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
 String stringDate = sdf.format(date );
    try {
        Date date2 = sdf.parse(stringDate);
    } catch(ParseException e){
     //Exception handling
    } catch(Exception e){
     //handle exception
    }
Dmitriy
  • 5,525
  • 12
  • 25
  • 38
Kanchan
  • 870
  • 1
  • 9
  • 20
  • FYI, while correct this Answer is now outmoded. The classes used here are troublesome and flawed, now supplanted by the modern java.time classes. – Basil Bourque Nov 07 '17 at 14:31
4

Use DateFormat#parse(String):

Date date = dateFormat.parse("2013-10-22");
qqilihq
  • 10,794
  • 7
  • 48
  • 89
1

tl;dr

How to convert date to string and to date again?

LocalDate.now().toString()

2017-01-23

…and…

LocalDate.parse( "2017-01-23" )

java.time

The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.

Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.

If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;

ISO 8601

Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.

That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse and LocalDate::toString without specifying a formatting pattern.

String s = ld.toString() ;

To parse:

LocalDate ld = LocalDate.parse( s ) ;

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.

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
  • Can you point me to a source that backs up your "that default can change at any moment during runtime, and so is unreliable." claim? I found this very surprising. – omajid Nov 07 '17 at 14:55
  • @omajid [`TimeZone.setDefault`](https://docs.oracle.com/javase/9/docs/api/java/util/TimeZone.html#setDefault-java.util.TimeZone-) may be called by any code in any thread of any app within a JVM *during* runtime. The change immediately affects all other code running in all the threads of all the apps within that JVM. Quite unpredictable and beyond your control as a programmer. Always specify your desired/expected time zone explicitly by passing the optional [`ZoneId`](https://docs.oracle.com/javase/9/docs/api/java/time/ZoneId.html) argument. – Basil Bourque Nov 07 '17 at 16:51
0

try this function

public static Date StringToDate(String strDate) throws ModuleException {
    Date dtReturn = null;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
    try {
        dtReturn = simpleDateFormat.parse(strDate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dtReturn;
}
Yasa
  • 332
  • 4
  • 21
0

Convert Date to String using this function

public String convertDateToString(Date date, String format) {
        String dateStr = null;
        DateFormat df = new SimpleDateFormat(format);
        try {
            dateStr = df.format(date);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return dateStr;
    }

From Convert Date to String in Java . And convert string to date again

public Date convertStringToDate(String dateStr, String format) {
        Date date = null;
        DateFormat df = new SimpleDateFormat(format);
        try {
            date = df.parse(dateStr);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return date;
    }

From Convert String to date in Java

David Pham
  • 1,673
  • 19
  • 17