-1

In our project I have faced a problem that is

Date date = new Date();

is converted to string

String dateToString = date.toString();

Again I want to convert same string (dateToString) as util date.

Any Solution?

Some Code Snippet:

    Date todayDate = new Date();
    String dateToString = todayDate.toString();
    System.out.println(dateToString);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM hh:mm a YYYY");
    Date stringToDate = new Date("05/26/2016");
    System.out.println(stringToDate);

Output is: Thu May 26 18:12:58 IST 2016 Thu May 26 00:00:00 IST 2016 Here second output instead of 0's I need exact time. That's it.

maheshd
  • 13
  • 6

3 Answers3

1

Use Date.valueOf(dateToString).

Thomas B Preusser
  • 1,159
  • 5
  • 10
0

You need to use a date format so that you can predictably be able to parse it back to date:

java.text.DateFormat format = new java.text.SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy");
String dateToString = format.format(date);

//And to parse it back to date:
Date parsedDate = format.parse(dateToString);

This code uses a format to write the date as a string, you can read more about this starting with the JavaDocs of java.text.DateFormat. The same format object is used to convert the string back to date.

The only common denominator is the format that you use to write the date as a string.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
0

Lets Try this way you will get I hope

String DATE_FORMAT_NOW = "dd MMM hh:mm:ss yyyy";
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String stringDate = sdf.format(date );
System.out.println("FirstDate : "+stringDate);
try {
    Date date2 = sdf.parse(stringDate);
    System.out.println(date2);
    } catch(ParseException e){
      //Exception handling
       } catch(Exception e){
         //handle exception
       }
IamDMahesh
  • 99
  • 1
  • 10