-3

I have a Date in this format:

Tue Mar 10 00:00:00 UTC 1987

It is stored in a Object Date.

Object tmp = solrDoc.getFieldValue("date_from")

I would like to convert it to a strictly numeric format, without the hours, timezone etc., like

10.03.1987

This is what I tried so far:

DateFormat date = new SimpleDateFormat("dd.MM.yyyy");
date.format(tmp);

It returns:

 "java.text.SimpleDateFormat@7147a660"
Lazar Zoltan
  • 135
  • 3
  • 14
  • 3
    Convert the `Object` to `Date` and then pass it to the converter. – NiVeR Apr 11 '18 at 13:42
  • 1
    You need `String formattedDate = date.format(tmp);`. – OldCurmudgeon Apr 11 '18 at 13:42
  • If you have date in such format, then `dd.MM.yyyy` will not work at all. – M. Prokhorov Apr 11 '18 at 13:53
  • @OldCurmudgeon this solved my problem.. I kinda always struggle with date datatypes.. – Lazar Zoltan Apr 11 '18 at 14:09
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 11 '18 at 16:19
  • Please search before asking. Formatting of dates has been covered literally hundreds of times already. So you’ll find a good answer much faster that way. – Ole V.V. Apr 11 '18 at 16:20

1 Answers1

2

You're attempting to use the format method on an Object, but according to the documentation, you need to pass this method a Date. So what you actually need to do is parse that original String into a Date, then format that.

For example, you could do it like this:

String tempString = String.valueOf(solrDoc.getFieldValue("date_from"));
DateFormat formatToRead = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
DateFormat formatToWrite = new SimpleDateFormat("dd.MM.yyyy");
formatToWrite.setTimeZone(TimeZone.getTimeZone("UTC"));
Date tempDate = null;
String result = null;
try {
    tempDate = formatToRead.parse(tempString);
} catch(ParseException e){
    e.printStackTrace();
}
if(tempDate != null){
    result = formatToWrite.format(tempDate);
    System.out.println(result);
}

Note that I had to set the TimeZone on the formateToWrite in order to keep it in UTC.

If you want more information on the SimpleDateFormat that I used to parse your original String, please refer to this SO answer.

Francis Bartkowiak
  • 1,374
  • 2
  • 11
  • 28
  • I was close, the thing I didn't do is to store the formated value in a String object.. after I did that, it worked just fine.. Thank you for your answere – Lazar Zoltan Apr 11 '18 at 14:13