79424454

Date: 2025-02-09 05:55:49
Score: 1
Natty:
Report link

TL;DR

    Date date = new Date();
    Instant instant = date.toInstant();
    System.out.println(instant);

2025-02-09T05:50:01.737Z

java.time

Since Java 8 use java.time, the modern Java date and time API, for your date and time work. The classes Date and SimpleDateFormat that you were trying to use were badly designed and for that reason supplanted by java.time in Java 8 in 2014. So the above code assumes that you got a Date from a legacy API not yet upgraded to java.time. If not, do not use Date at all.

You are asking the impossible

You said

… I want to ISO-8601 in UTC format(2013-20-02T04:51:03Z). I want to return convertedDate value in Date format (not as String format).

Neither could a Date nor can any of the modern date-time types have a format. Formatted dates come in strings.

java.time brings you somewhat closer than Date ever could, though. The modern types print in ISO 8601 format. Their toString methods produce it. This is why the above quoted output is in ISO 8601 format.

Your example output did not have fraction of second. My output has three decimals (milliseconds). This is fine since the fraction is optional according to ISO 8601. If you want an Instant without the fraction, again, you can’t, but you can simulate it easily. An Instant always has nanosecond precision, but if the fraction is zero, the toString method does not print it.

    Instant instant = date.toInstant().truncatedTo(ChronoUnit.SECONDS);
    System.out.println(instant);

2025-02-09T05:50:01Z

Your title and text are lying

Your question is confused. Your title and text talk about a “timestamp” in Wed, 20 Feb 2013 11:41:23 GMT (EEE, d MMM yyyy HH:mm:ss GMT) format. But your code contains no such format. It gets a String from Date.toString() and tries to parse it. Your exception message quotes Wed Feb 20 03:50:03 PST 2013, which was the return value of Date.toString() and hence agrees with the code.

If you did mean that you had a String like Wed, 20 Feb 2013 11:41:23 GMT (RFC 822 or RFC 1123 format), use the good answer by Basil Bourque demonstrating the elegant and easy way that java.time handles this format.

The reason for your exception was that you tried to parse the string using the format that you wanted to have. Had you needed to parse the string (which you didn’t since you already had a Date object), you should have specified the format that was in the string, not the desired format.

Tutorial link

Oracle Tutorials: Trail: Date Time

Reasons:
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: Sara Beridze