-2

Hey there I have a question regarding the way that Java parses or formatts a Date.

I have this code:

private DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.FULL, Locale.GERMAN);
private DateFormat dateFormatter2 = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMAN);

...

        String dateTest = dateFormatter.format(Long.parseLong(pair.getKey().get(3)));
        String dateTest2 = dateFormatter2.format(Long.parseLong(pair.getKey().get(3)));

            System.out.println("dateTest: " + dateTest + " || dateTest2: " + dateTest2);

This gives me following result:

dateTest: Donnerstag, 2. Februar 2023 || dateTest2: 02.02.2023

Now I want to convert the date to this Format: "yyyy-MM-dd". I tried with simpledateformatter and the Parse function but always ended up in Errors like this:

 java.text.ParseException: Unparseable date: "02.02.2023" 

How can I simply change the date to my desired format? Would be cool if the result was of type Date.

DateFormatter only shows me how to do it from a Date but I have a String. The Problem is that I dont know how to change the String into a Date.

new Date(string) and (Date) string do not work.

Edit:

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
            LocalDate date = LocalDate.parse(dateTest2, formatter);
            System.out.println("NewDate " + date); 

result is:

SEVERE: Uncaught Exception
java.time.format.DateTimeParseException: Text '01.02.2023' could not be parsed at index 0
yesIamFaded
  • 1,970
  • 2
  • 20
  • 45
  • https://www.baeldung.com/java-datetimeformatter – Stultuske Feb 02 '23 at 11:10
  • The thing is that it only tell me how to format a date in the dateformatter but I have a string. Could you tell me how to format that string to a date first? new Date(string) or (Date) string do not work. – yesIamFaded Feb 02 '23 at 11:20
  • 4
    You don't *format* a string to a date - you *parse* a string to a date. Hopefully that clue will help you in your research. But I'd *strongly* recommend that you use java.time instead. And given that it looks like your data *actually* starts with a `long` value, not a string, it sounds like you don't really need to do that anyway... If you find yourself formatting a value and then parsing the result, try to find a way of going straight from the original value to the desired result *without* string conversions. – Jon Skeet Feb 02 '23 at 11:24
  • @JonSkeet well honestly I dont get it.. I tried to parse the date again but it just does not work :/ Edited my Question maybe someone knows whats going on. – yesIamFaded Feb 02 '23 at 11:33
  • 1
    Since I understand from your code that `pair.getKey().get(3)` returns a *`String`*, I suggest looking at these similar questions: [Convert Timestamp in numerical format to LocalDateTime in Java](https://stackoverflow.com/questions/65199689/convert-timestamp-in-numerical-format-to-localdatetime-in-java) and [Trying to create a timestamp "mm/dd/yyyy hh:mm a" for a chat for android using java](https://stackoverflow.com/questions/59445645/trying-to-create-a-timestamp-mm-dd-yyyy-hhmm-a-for-a-chat-for-android-using-j). – Ole V.V. Feb 02 '23 at 16:43

2 Answers2

4

You probably need something like:

LocalDate date = Instant.ofEpochMilli(Long.parseLong(pair.getKey().get(3))).atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(date);

If you have to have Date, you can do:

Date d = Date.from(Instant.ofEpochMilli(Long.parseLong(pair.getKey().get(3))));
g00se
  • 3,207
  • 2
  • 5
  • 9
  • Jesus Christ that actually works :D Thanks man I have no Idea how someone actually is able to know that this is the way to format in my case. Thanks. One more thing tho: this is a localdate how would you change it to a "normal" Date? – yesIamFaded Feb 02 '23 at 11:51
  • Ok I found a Function to convert it from LocalDate to Date. – yesIamFaded Feb 02 '23 at 11:59
  • 2
    No - that's the wrong way around. You should be using the new date/time api as I showed. Why do you think you need `Date`? – g00se Feb 02 '23 at 12:32
  • Because I have functions that need the variable to be Date not LocalDate. – yesIamFaded Feb 02 '23 at 12:37
  • That's a shame. But there's a further issue in that case. Presumably, you're aware that `Date` contains *time* info? Is that time info actually *used*? – g00se Feb 02 '23 at 12:38
  • Mh yeah I see that beacuse actually I am getting this back: Thu Feb 02 00:00:00 CET 2023 so its not even the format I wanted but as it is a date it gets handled correctly by my following functions and calls. As of now everything works as expected for me ^^ – yesIamFaded Feb 02 '23 at 12:42
  • Good. Keep an eye on that and see my edit above – g00se Feb 02 '23 at 12:46
  • Yeah thanks ended up using your Edit because it is shorter - ty. – yesIamFaded Feb 02 '23 at 13:02
  • 1
    `Date.from(Instant.ofEpochMillis(x))` is still a very long-winded way of writing `new Date(x)` - see my answer, now that it's clearer that what's desired (a java.util.Date from a long) has nothing to do with text representations. – Jon Skeet Feb 02 '23 at 14:01
3

If you just need to get a java.util.Date from a long value which is the number of milliseconds since the Unix epoch, it really is trivial:

long millis = Long.parseLong(pair.getKey().get(3));
Date date = new Date(millis);

Or inlined if you really want to:

Date date = new Date(Long.parseLong(pair.getKey().get(3)));

I would strongly advise you to try to migrate all your code to java.time though. It's a far superior API.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194