I have a question. I need to convert and display the data from database which it's a timestamp to date format only. *the format is dd/MM/yyyy
Currently I writng the code like this but the error says "Cannot format given Object as a Date"
xi.setItem("Dte",db.getDataAt(i,
new SimpleDateFormat("dd/MM/yyyy").format("date_column_from_db")));
this is the example of the date column in the database: 20220321211529042 (basically it is a timestamp)
and I want to convert and display the data to date format only, like this: 21/03/2022
Hope to get solution. Thank you!
CodePudding user response:
Your use of the term 'timestamp' is misleading - it is really an encoded string.
You will need to decode the DB string and then recode it in the new format you want. Something like:
String timestring = "20220321211529042";
var parsedTimestamp = DateTimeFormatter.ofPattern("yyyyMMdd").parse(timestring.substring(0, 8));
System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy").format(parsedTimestamp));
In this case I've used substring
to discard the time portion but if you want that you could extend the formatter used for parsing to include it.
CodePudding user response:
Just test the below code, format()
method only allows Date
or Number
as an argument, String
is invalid.
String column = new SimpleDateFormat("dd/MM/yyyy").format(20220321211529042L);
System.out.println("column = " column);
DateFormat
source may be more detailed https://developer.classpath.org/doc/java/text/DateFormat-source.html
public final StringBuffer format(Object obj, StringBuffer toAppendTo,
FieldPosition fieldPosition)
{
if (obj instanceof Date)
return format( (Date)obj, toAppendTo, fieldPosition );
else if (obj instanceof Number)
return format( new Date(((Number)obj).longValue()),
toAppendTo, fieldPosition );
else
throw new IllegalArgumentException("Cannot format given Object as a Date");
}