1
String sDate = "06.08.2020" // 06 day 08 month 2020 is year

This is the date i have in my txt file. I use them in JTable. To sort the table i convert them to date with this DateFormatter.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");

And it does convert the string to date as this.

LocalDate date = LocalDate.parse(sDate,formatter);
//The date : Thu Aug 06 00:00:00 TRT 2020

Now i need to convert it like the first date 06.08.2020. But i can't use date as input. Because i get it from JTable so i get it as String.

So i tryed this code.

String sDate1 = "Thu Aug 06 00:00:00 TRT 2020";// The date i get from JTable
LocalDate lastdate = LocalDate.parse(sDate1,formatter);
sDate1 = formatter.format(lastdate);

But i get an error as this Text 'Thu Aug 06 00:00:00 TRT 2020' could not be parsed at index 0.

So this cone not works fine : LocalDate lastdate = LocalDate.parse(sDate1,formatter); I cant see where is the problem.

Gresta
  • 72
  • 8
  • 7
    **You should definitely stop using `Date` and `SimpleDateFormat`** – they're obsolete. Use classes from the `java.time` package instead. – MC Emperor Aug 31 '20 at 16:20
  • @MCEmperor i will check it now. Thanks for the tip sir. – Gresta Aug 31 '20 at 16:33
  • 2
    I found the answers in [this question](https://stackoverflow.com/questions/32437550/whats-the-difference-between-instant-and-localdatetime) to be a helpful overview for `java.time`. – andrewJames Aug 31 '20 at 16:56
  • 1
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Aug 31 '20 at 17:50
  • I cannot reproduce. I suspect that your exception may come from code that you haven’t shown us and that you also don’t need. – Ole V.V. Aug 31 '20 at 17:57
  • @OleV.V. the error line is (parse) part. So i just cant convert the String to Date. – Gresta Aug 31 '20 at 18:26
  • 1
    `String date = "06.08.2020";` = you have a String in `dd.MM.yyyy` format, and then you try to **parse** _that string_ `sdf1.parse(date)` using the format `EEE MMM dd HH:mm:ss z yyyy` — I would _expect_ that to fail. The date-string that you are trying to parse is _not in the format_ that the parser expects. – Stephen P Aug 31 '20 at 18:51
  • 1
    Strings representing dates will sort correctly if they are in the form "yyyyMMdd" without having to convert them to actual dates or timestamps — `String sortableDateString = inputDateString.replaceAll("(\\d\\d)\\.(\\d\\d)\\.(\\d{4})", "$3$2$1");` – Stephen P Aug 31 '20 at 19:01
  • 1
    `sdf1.parse(date)` throws `java.text.ParseException: Unparseable date: "06.08.2020"`, not the exception you quoted. With `sdf` instead `sdf1` it doesn’t throw any exception. – Ole V.V. Aug 31 '20 at 19:20
  • @OleV.V. i changed the post with java.time but still getting same error and i hope i explained my problem better now. – Gresta Sep 01 '20 at 09:02
  • Thanks. Somehow related: [Why am I getting a parse exception when I try to parse the current LocalDateTime \[duplicate\]](https://stackoverflow.com/questions/58012504/why-am-i-getting-a-parse-exception-when-i-try-to-parse-the-current-localdatetime). – Ole V.V. Sep 01 '20 at 09:06

2 Answers2

3

I cannot reproduce the behaviour you describe. The following code worked fine for me:

import java.util.*;
import java.text.*;
public class MyClass {
    public static void main(String args[]) throws ParseException {
      SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
      String date = "06.08.2020";
      Date date1 = sdf.parse(date);
      String result = sdf.format(date1);

      System.out.println("Date = " + result);
    }
}

Output: Date = 06.08.2020

That being said, if at all possible you should switch to the new java.time.* API.

JustAnotherDeveloper
  • 2,061
  • 2
  • 10
  • 24
  • The problem is i cant get "date1" as a date. I can get it as String. When i try your code it works fine. But when i convert date1 to String then i try to parse it. I get "Unparseable date" error. – Gresta Aug 31 '20 at 16:50
  • 2
    But my code gets date1 as a date. And then converts it to a string. If you can't reproduce it, then that means your input differs from what I used as input, it's the only way you'd get that error. If you literally copy my code as is, compile it and run it, with the same input, it should, and will, produce the same output. – JustAnotherDeveloper Aug 31 '20 at 16:52
  • as i said the code works fine. And i use same SimpleDateFormat for my all codes. The thing is, i get the date from the table. The user select the date. So i cant know what date i should convert. I get the Date as String from txt and convert it to Date to write to the JTable. After that i need the date. But as you know i cant get it as Date from JTable so i have to convert it. But i get the error i said. – Gresta Aug 31 '20 at 18:23
  • 1
    @Gresta - you get a date that was selected by the user from a table, you get `dd.MM.yyyy` but _**you**_ are the one choosing `"EEE MMM dd HH:mm:ss z yyyy"`to use in your SimpleDateFormat — you don't have to choose that format to get a sortable date, and it's especially pointless to include the timezone. And as _everyone_ is saying, if this is a new piece of code you're writing, use the `java.time.*` package instead. – Stephen P Aug 31 '20 at 18:48
  • @StephenP i understand what you said. Dont mind me if i explained wrong. I was trying to say, i cant get the input as a date. I have to get it as a String. And thats the different between the my code and JustAnotherDeveloper's code. And i will check the java.time.* right now. Thanks – Gresta Aug 31 '20 at 19:12
  • 1
    @Gresta: My code uses a String as input. If you get it from a table, you can probably restrict the format in which the date must be entered in the table (or if it's retrieved from a database, you should know in which format it is stored), so there's no reason why not knowing your exact input should be a problem. Furthermore, if you get that error with the String you retrieve from the JTable, the problem is, as I predicted, that your input does not follow the pattern with which you've built your date formatter. – JustAnotherDeveloper Aug 31 '20 at 19:46
  • @JustAnotherDeveloper now i edit the code with more detail. I understand what you said but i use same formatter for everything. But still getting the error. – Gresta Sep 01 '20 at 09:04
  • 1
    @Gresta: I have literally copied your code into an online IDE and it works, you can check it here and see that it prints the date in the specified format: [https://jdoodle.com/ia/CK](https://jdoodle.com/ia/CK) TRT is the timezone indicator for Turkey official time. There is definitely something in your input or your formatter that makes it not the input or formatter you are telling us you use, because that TRT does not magically appear out of nowhere. – JustAnotherDeveloper Sep 01 '20 at 09:12
  • @JustAnotherDeveloper My code more complext then this. The formatter convert the date as not i want so i use multiple `DateTimeFormatter` and thats kinda fixed my problem. Thanks for the helps. – Gresta Sep 01 '20 at 09:32
2

Where your code failed:

SimpleDateFormat sdf1=new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
String dateStr = "06.08.2020";
sdf1.parse(dateStr);

As you can see, the pattern of the SimpleDateFormat and that of the date string do not match and therefore, this code will throw ParseException.

How to make it work?

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);

You must have already got why it worked. It worked because the pattern of the SimpleDateFormat matches with that of the dateStr string.

Can I format the Date object (i.e. date) into the original string?

Yes, just use the same format which you used to parse the original string as shown below:

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String dateStr = "06.08.2020";
Date date = sdf.parse(dateStr);

// Display in the default format
System.out.println(date);

// Format into the string
dateStr = sdf.format(date);
System.out.println(dateStr);

A piece of advice:

I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time.

Using the modern date-time API:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
String dateStr = "06.08.2020";
LocalDate date = LocalDate.parse(dateStr, formatter);

// Display in the default format
System.out.println(date);

// Format into the string
dateStr = formatter.format(date);
System.out.println(dateStr);

I don't see any difference using the legacy API and the modern API:

That's true for this simple example but when you will need to do complex operations using date and time, you will find the modern date-time API smart and clean while the legacy API complex and error-prone.

Demo:

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Given date-time string
        String strDate = "Thu Aug 06 00:00:00 TRT 2020";

        // Replace TRT with standard time-zone string
        strDate = strDate.replace("TRT", "Europe/Istanbul");

        // Define formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzzz yyyy");

        // Parse the date-time string into ZonedDateTime
        ZonedDateTime zdt = ZonedDateTime.parse(strDate, formatter);
        System.out.println(zdt);

        // If you wish, convert ZonedDateTime into LocalDateTime
        LocalDateTime ldt = zdt.toLocalDateTime();
        System.out.println(ldt);
    }
}

Output:

2020-08-06T00:00+03:00[Europe/Istanbul]
2020-08-06T00:00
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Thanks for the answer sir. I changed my code as your advice. But i still get the error. And now i explained more details. As i said before i cant use your *date* as you did. I have to get it as *String*. Convert it to *Date* and convert to *String* again. If i do as you did no problem. But when i try to get *Date* as *String*, i get teh error. – Gresta Sep 01 '20 at 09:07
  • @Gresta - I've added an update which should fulfil your requirement. Feel free to comment in case of any doubt/issue. – Arvind Kumar Avinash Sep 01 '20 at 09:21