How to convert Date.toString back to Date?

I have a string obtained by calling an toStringinstance method of the Date class.
How can I get a Date object from this string?

Date d = new Date();
String s = d.toString;
Date theSameDate = ...

UPDATE
I tried to use SimpleDateFormat, but I get. java.text.ParseException: Unparseable date Can you tell me the date format created by Date.toString ()?

+5
source share
5 answers

If your real goal is to serialize the object Datefor any personalized persistence or data transfer, a simple solution would be:

Date d = new Date();
long l = d.getTime();
Date theSameDate = new Date(l);
+12
source

You can do it like this:

Date d = new Date();
String s = d.toString;
Date theSameDate = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(s);
+8
source
  • (, ), ISO 8601, .
  • Date. Java-API , java.time, . , , , Instant ( ).

:

    Instant i = Instant.now();
    String s = i.toString();
    Instant theSameInstant = Instant.parse(s);

toString ISO 8601 (, 2018-01-11T10:59:45.036Z), parse . , - , , , , .

, , Date.toString(), Sedalbs java.time:

    DateTimeFormatter dtf 
            = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
    Date d = new Date();
    String s = d.toString();
    Instant nearlyTheSameInstant = ZonedDateTime.parse(s, dtf).toInstant();

. JVMs, , . , , , - .

jambjos answer - : , Date.toString(), , , , , , - JVM.

Finally, it Date.toString()does not display the milliseconds that matter Date, which leads to inaccuracies of up to 999 milliseconds. If we use the string from Date.toString(), we can do nothing with it (which is why I named the variable nearlyTheSameInstant).

+2
source

Date theSameDate = new Date(Date.parse(s));

For some not so obvious reasons, this is not a good idea. Details on this can be found in the API documentation for the analysis method. One problem is, for example, that time zone abbreviations are ambiguous, so the parser may not interpret the correct time zone.

-1
source

All Articles