This question already has answers here:
Java : Cannot format given Object as a Date
(7 answers)
LocalDateTime.parse(yyyMMddHHmmssSSS, DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS") error [duplicate]
(1 answer)
Change date format in a Java string
(22 answers)
Dates with no time or timezone component in Java/MySQL
(6 answers)
Closed last month.
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!
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:
var timestring = "20220321211529042";
var parsedTimestamp = DateTimeFormatter.ofPattern("uuuuMMddHHmmssSSS").parse(timestring);
var output = DateTimeFormatter.ofPattern("dd/MM/yyyy").format(parsedTimestamp);
As an alternative, you can use an intermediate LocalDateTime variable:
var timestring = "20220321211529042";
var dateTime = LocalDateTime.parse(timestring, DateTimeFormatter.ofPattern("uuuuMMddHHmmssSSS"));
var output = dateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
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");
}
Related
This question already has answers here:
Good way to convert integer YYYYMMDD into java.util.Date with local time zone
(4 answers)
How can I convert an Integer (e.g 19000101 ) to java.util.Date?
(5 answers)
Type mismatch: cannot convert from java.util.Date to java.sql.Date
(3 answers)
Closed 2 years ago.
I want to convert an int value to a date.
For example, 20200605 is 2020-06-05
This is my code, Why doesn't it work?
public static void main(String[] args) {
int value = 19000101;
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse(Integer.toString(value));
SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd");
String formatedDate = newFormat.format(date);
}
I am getting an error on this line.
Date date = originalFormat.parse(Integer.toString(value));
The error message is
Type mismatch: cannot convert from java.util.Date to java.sql.Date
I don't know what it means.
The error you get:
Type mismatch: cannot convert from java.util.Date to java.sql.Date
tells that you have imported a wrong Date object. Please check at the top of the class. You will need to replace import java.sql.Date; with import java.util.Date;
I don't know much about the Date and SimpleDateFormat classes in java, but this should be fairly easy to do anyway without it.
String date_str = ""+value;
String formattedDate = date_str.substring(0,4)+"-"+date_str.substring(4,6)+"-"+date_str.substring(6,8);
This question already has answers here:
Convert String Date to String date different format [duplicate]
(8 answers)
Format String yyyy-mm-dd hh:mm:ss +timezone into DateTime
(2 answers)
Converting String to Date using SimpleDateFormat is returning random date [duplicate]
(2 answers)
Closed 3 years ago.
I wrote a method to parse a date. When I'm passing the following date as an argument 2019-03-05 06:15:00, I'm getting a java.text.ParseException: Unparseable date: "2019-03-05 06:15:00".
What could be wrong with the logic?
public String convertDate(String val) throws ParseException {
return "cast('" + new SimpleDateFormat("yyyy-MM-dd HH:mm:SS").format(
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'").parse(val)) + "' as ts)";
}
You are trying to parse string 2019-03-05 06:15:00 using pattern yyyy-MM-dd'T'HH:mm'Z' that obviously does not fit.
Either change the method to following
public String convertDate(String val) throws ParseException {
return "cast('" + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'").format(
new SimpleDateFormat("yyyy-MM-dd HH:mm:SS").parse(val)) + "' as ts)";
}
or pass
2019-03-05T06:15Z
Well, nothing is wrong with your code except for this SS and change the order too.
s second-of-minute number 55
S fraction-of-second fraction 978
public static String convertDate(String val) throws ParseException {
return "cast('" + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'").format(
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(val)) + "' as ts)";
}
The Z represents the zone offset. Per documentation
Z zone-offset offset-Z +0000; -0800; -08:00;
So your String should be, for example
2019-03-05T06:15+0100
Your patterns doesn't seem to reflect what you want to accomplish. Z isn't just a simple letter.
yyyy-MM-dd'T'HH:mmZ
Anyway, avoid using SimpleDateFormat, use DateTimeFormatter instead, which is part of the new Time API for Java 8.
final String val = "2019-03-05T06:15+0100";
final TemporalAccessor parse = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmZ").parse(val);
final String format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:SS").format(parse);
By inputting
2019-03-05T06:15+01:00
you could even just use
final TemporalAccessor parsed = DateTimeFormatter.ISO_DATE_TIME.parse(val);
This question already has answers here:
Java string to date conversion
(17 answers)
Closed 6 years ago.
I need to convert date string into a another specific format.
For example: I've a date which can come as YYYY-MM-DD or YYYY-MM-DDThh:mm:ss±0000 and I need to convert that to something "yyyy-mm-ddTHH:MM:SSZ".
I tried few things using Java 8 API but could not find a way out.
Try this (Java 8):
String input = "2016-10-14T14:19:40-04:00";
String output = ZonedDateTime.parse(input).toInstant().toString();
System.out.println(output); // prints 2016-10-14T18:19:40Z
This works because the primary format of ZonedDateTime used by parse() is ISO_ZONED_DATE_TIME, so it will parse input in the format you described.
The output format you requested happens to be the default format of Instant, as returned by its toString() method, i.e. the ISO_INSTANT format.
Converting between the two (ZonedDateTime to Instant using the toInstant() method) will perform the timezone adjustment necessary.
Try this:
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd"); // or "YYYY-MM-DDThh:mm:ss±0000"
String dateInString = "1993-11-27";
Date date = inputFormat.parse(dateInString);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ssZ");
System.out.println(outputFormat.format(date));
This question already has answers here:
Java string to date conversion
(17 answers)
Closed 9 years ago.
I have a String value which I need to convert into time and save it in the MySQL.[The column's datatype is time in the database table]
The examples of String values that I might encounter to convert into time object are:
String time = "5:32 PM";
String time = "12:00 AM";
String time = "11:43 PM";
I browsed for few examples which pulled the time from the Date object but couldn't find an apt example, such as in this case to convert it from a plain string. The main reason I need to convert it to time is to save it in the mysql.
You can convert it to java.sql.Date as :
String str = "5:32 PM";
DateFormat formatter = new SimpleDateFormat("hh:mm a");
java.util.Date date = (java.util.Date)formatter.parse(str);
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
If you need java.sql.Time , then :
java.sql.Time time = new java.sql.Time(date.getTime());
And then use PreparedStatement#setTime().
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I am writing this section of code to compare a query to the database with the current date in order to tell if a student is already checked into class. I can cast them both to string and they look identical but they are different in some way at a byte level and the if statement is still returning false. What can be done?
Also this does not work.
java.sql.Date date = new Date();
It gives an error that is why I tried changing the format to .sql.Date with the first 2 lines. It did not help but I left it in there to show what I have tried.
here is the code
public boolean checkTodaysAttendance(int ID){
//date stuff
java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
//System.out.println(sqlDate);
boolean attend = false;
try {
PreparedStatement statement = con.prepareStatement("SELECT Date FROM attendance WHERE ID="+ID);
rs1 = statement.executeQuery();
while(rs1.next()) {
//System.out.println(rs1.getDate("Date"));
if (rs1.getDate("Date").toString().trim(). == sqlDate.toString().trim()) { //my problem is on this line
attend = true; //string don't equal at a byte level
}
}
}catch(Exception ex){
System.out.println(ex);
}
//System.out.println(attend);
return attend;
}
Change both dates to strings using simple date format and then compare.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
// create a new String using the date format we want
String dateString= formatter.format(date);