Hello Guys I am facing problem with casting date that I retrieve from Ms access DB to JDateChooser, but a message appear to me telling java.util.Date cannot be cast to java.util.Date..
String sql="select * from Patient where PatientID=?"; try{
ps=con.prepareStatement(sql);
ps.setString(1, txt_PID.getText());
rs=ps.executeQuery();
if(rs.next()){
// String add1=rs.getString("PatientID");
// txt_PID.setText(add1);
String add2=rs.getString("PatientName");
txt_PName.setText(add2);
String add3=rs.getString("PatientGender");
cmb_PGender.setSelectedItem(add3);
String add4=rs.getString("PatientAge");
txt_PAge.setText(add4);
String add5=rs.getString("PatientType");
cmb_PType.setSelectedItem(add5);
String add6=rs.getString("PatientGSM");
txt_PGsm.setText(add6);
String add7=rs.getString("Patient_Maj_Jop");
txt_major_Jop.setText(add7);
DateFormat formatter ;
Date date1;
String add8=rs.getString("DateOfReg");
formatter = new SimpleDateFormat("MMM d, yyyy");
date1 = (Date)formatter.parse(add8);
dch_Date.setDate(date1);
table_PatuentReg.setModel(DbUtils.resultSetToTableModel(rs));
} }catch(Exception e){ JOptionPane.showMessageDialog(null, e.getMessage());
}
if(txt_PID.getText().equals("")){
Update_Table();
}
Without looking at date1 variable, I'm guessing you might be using java.sql.Date? Check you are indeed using java.util.Date.
Show us your import statements.
The problem is with this line because DateFormatter is returning you an instance of java.util.Date and you are trying to cast it to a java.sql.Date which it isn't.
date1 = (Date)formatter.parse(add8);
Easy fix is to import java.util.Date instead. I don't see there is a need for you to use java.sql.Date as you are not fetching Date SQL colum, are you?
Related
I am getting date and time from store. In data base its look like this
Need to know how can I show this as DD/MM/YY
I am trying to do like this
String timeString = snapshot.data[index]['lastupdate'].toString();
DateTime date = DateTime.parse(timeString);
print(DateFormat('yyyy-MM-dd').format(date));
Its showing error of Invalid date format
Try like this your lastupdate date is not convertime inDate thats why its showing error
DateTime date = DateTime.parse(snapshot.data[index]['lastupdate'].toDate().toString());
print(DateFormat('dd-MMM-yyy').format(date));
Use function to get date from Timestamp like this:
readDate(Timestamp dateTime) {
DateTime date = DateTime.parse(dateTime.toDate().toString());
// add DateFormat What you want. Look at the below comment example
//String formatedDate = DateFormat('dd-MMM-yyy').format(date);
String formatedDate = DateFormat.yMMMMd().format(date);
return formatedDate;
}
Use the function when you want it.
For example:
Text(readDOB(streamSnapshot.data!["dob"]))
For this you should install intl package. read
MongoCollection<Document> Profile_List = db.getCollection("Profile_List");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
Date todaydate = format.parse(new Date().toString());
ArrayList<Document> activeList=profile.find(Filters.regex("lastActive",todayDate.toString())).into(new ArrayList<Document>());
This is the code what we have written. We are getting an “Unparseable date error”. Can someone please help?
This is wrong:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
Date todaydate = format.parse(new Date().toString());
The expression new Date().toString() does not return a string that conforms to the format yyyy-MM-DD, so if you try to parse it as if it is formatted that way, you will get an exception.
If you want a Date object that represents the current date and time, simply do this:
Date todaydate = new Date();
No need to convert the Date object to a string and trying to parse it.
If you need a string with the current date in the format yyyy-MM-dd then do this:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String todaydate = format.format(new Date());
Note: You used DD in your date format string but you most likely meant dd. See the API documentation of SimpleDateFormat.
If you are trying to get the current date string in yyyy-MM-dd format. You can do format it like this
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = simpleDateFormat.format(new Date());
I believe this should work. Granted it has no specified offset, but shouldn't that then default to UTC? And if not, how can I parse a string like this into an OffsetDateTime?
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd['T'[HH:mm:ss][.SSSSS]][z][x]");
String datetime = "2018-12-03T18:07:55";
OffsetDateTime odt = OffsetDateTime.parse(datetime, formatter);
Exception thrown:
java.time.format.DateTimeParseException: Text '2018-12-03T18:07:55' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {},ISO resolved to 2018-12-03T18:07:55 of type java.time.format.Parsed
As you say, it's failing because there's no offset in the format. To work around this, you can use the same format to parse to a LocalDateTime, and then combine with a ZoneOffset to create an OffsetDateTime:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd['T'[HH:mm:ss][.SSSSS]][z][x]");
String datetime = "2018-12-03T18:07:55";
LocalDateTime ldt = LocalDateTime.parse(datetime, formatter);
OffsetDateTime odt = OffsetDateTime.of(ldt, ZoneOffset.UTC);
System.out.println(odt);
This question is similar to How to parse ZonedDateTime with default zone? but addinitional condition.
I have a string param that represent a date in UK format: "3/6/09". It doesn't contain time, only date. But may contain it and even time zone.
And I want to parse it to ZonedDateTime.
public static ZonedDateTime parse(String value) {
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(SHORT).withLocale(Locale.UK).withZone(ZoneId.systemDefault());
TemporalAccessor temporalAccessor = formatter.parseBest(value, ZonedDateTime::from, LocalDateTime::from, LocalDate::from);
if (temporalAccessor instanceof ZonedDateTime) {
return ((ZonedDateTime) temporalAccessor);
}
if (temporalAccessor instanceof LocalDateTime) {
return ((LocalDateTime) temporalAccessor).atZone(ZoneId.systemDefault());
}
return ((LocalDate) temporalAccessor).atStartOfDay(ZoneId.systemDefault());
}
But, it fails with exception:
java.time.format.DateTimeParseException: Text '3/6/2009' could not be parsed at index 6
It's a bug for me, or isn't?
In my opinion is not a bug. Your approach is flawed.
First of all you are returning a ZonedDateTime so it is expected that the String contains full date, time and zone information. The string "3/6/09" should be parsed to a LocalDate.
Second, you are delegating a runtime detection of format to the library. Again, you should be parsing/formatting an expected format. Your application should know wether is expecting a full date & time or a partial (only date or only time).
Anyway you will have more luck detecting the format and then using different parsing methods.
Only local date:
DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.parse(value, LocalDate::from)`
Zoned date and time:
DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT)
.parse(value, ZonedDateTime::from)`
The format used can be seen using the getLocalizedDateTimePattern() method:
String fmt = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT, FormatStyle.SHORT, IsoChronology.INSTANCE, Locale.UK);
The result is "dd/MM/yy HH:mm".
As such, the format is expecting both a date and a time with a space separator, so that is what must be provided.
In addition, the format/parse expects there to be two digits for the day-of-month and two digits for the month-of-year. Thus, you would need to pass in "03/06/09 00:00" in order to get the result you expect, in which case you can parse directly to a LocalDateTime.
Alternatively, use ofLocalizedDate():
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(Locale.UK);
LocalDate date = LocalDate.parse("03/06/99", formatter);
Note that the input must still have two digits for the day and month.
Alternatively, parse using a specific pattern that can handle the missing leading zeroes:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yy");
LocalDate date = LocalDate.parse("3/6/99", formatter);
LocalDate date = LocalDate.parse("03/06/99", formatter);
// handles both "3/6/99" and "03/06/99"
Update: Lenient parsing also handles this case:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseLenient().appendPattern("dd/MM/yy").toFormatter();
LocalDate date = LocalDate.parse("3/6/99", formatter);
LocalDate date = LocalDate.parse("03/06/99", formatter);
// handles both "3/6/99" and "03/06/99"
can anyone tell me how to do date validation in GWT please. im passing date as String. it should to be converted to date format and its format is to be validated.
import com.google.gwt.i18n.client.DateTimeFormat;
...
DateTimeFormat myDateTimeFormat = DateTimeFormat.getFormat(...);
Date date = myDateTimeFormat.parseStrict(dateString);
parseStrict() throws an IllegalArgumentException for invalid date strings.
You can use GWT Bean Validation pattern matching expression for String:
#Pattern( regexp = "some javascript regular expression" )
private String dateStr;
or this when you have date:
#DateTimeFormat(pattern = "dd.MM.yy")
private Date myStartDate;
I do not use this but you can see a complete sample in gwt-2.5.0 samples directory.
Have a nice time.