Hello I am trying to store the birthdate of the user in database with the code below:
private void btnActionPerformed(java.awt.event.ActionEvent evt) {
String username = txtUserName.getText();
String password = txtPassword.getText();
String email = txtEmail.getText();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthdate = sdf.format(JDateChooser.getDate());
Users user = new Users();
user.setUserName(cin);
user.setPassWord(firstName);
user.setEmail(email);
user.setBirthDate(birthdate);
try {
int count = Users.getInstance().insert(user);
if(count == 1){
JOptionPane.showMessageDialog(null,"success");
reset();
}else{
JOptionPane.showMessageDialog(null,"Faild");
}
} catch (Exception ex) {
Logger.getLogger(AddNewPatient.class.getName()).log(Level.SEVERE, null, ex);
}
}
I got an error which says String connot be converted to Date in the line "user.setBirthDate(birthdate);"
Because the parameter birthdate is assigned as Date type in the encapsulation(setBirthDate)
is there any way to solve this issue, I am new in java programming and I am trying to improve my skills in java.
If this returns a Date:
JDateChooser.getDate()
And what you need is a Date, then don't convert it to a String. Just keep it as a Date:
Date birthdate = JDateChooser.getDate();
// later...
user.setBirthDate(birthdate);
Note that you can then also remove this line, since you're not using the variable it declares:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
In general you want to keep data types in their raw form pretty much as often as possible. Unless there's a specific need for something to be represented as a string (displaying it to the user, sending it over a serialized API of some kind, etc.) then just use the data as-is instead of converting it to something else.
After you get the date with JDateChooser.getDate(), you are immediately converting it to a string: sdf.format(JDateChooser.getDate());
You should store the returned Date from JDateChooser.getDate() as an actual Date object.
Date birthdate = JDateChooser.getDate();
Then you can use it in your other function directly:
user.setBirthDate(birthdate);
If you do need the date as a string for some other purpose (perhaps display to the user), you can store a formatted string version in a different variable:
String birthdateString = sdf.format(birthdate);
Otherwise, if you don't need a string version, you can delete the line where you create sdf.
Related
Using h2o, I have used a .csv data frame that includes a column of dates, some of which are NULL, to train a model. Looking at the .hex dataframe that was output by h2o Flow UI after parsing the input .csv file, the null values are represented by .s and the remaining dates are represented as timestamp doubles (ie. milliseconds since epoch time).
When trying to use the model's MOJO file in a java program to make predictions, on a dataset, I am getting the error
Exception in thread "main" java.lang.NullPointerException
at hex.genmodel.easy.EasyPredictModelWrapper.fillRawData(EasyPredictModelWrapper.java:554)
at hex.genmodel.easy.EasyPredictModelWrapper.predict(EasyPredictModelWrapper.java:615)
at hex.genmodel.easy.EasyPredictModelWrapper.preamble(EasyPredictModelWrapper.java:489)
at hex.genmodel.easy.EasyPredictModelWrapper.predictBinomial(EasyPredictModelWrapper.java:303)
at SimpleCsvPredictor.predictCsv(SimpleCsvPredictor.java:287)
at SimpleCsvPredictor.main(SimpleCsvPredictor.java:210)
since I am handling NULL values in the dataset's date column by setting them t null in the RowData object that h2o's model EasyPredictionModelWrapper can make predictions on.
The problem is that, for this column, the model is expecting a Double value. But there is no Double value to pass in because the value is null. Note that I cannot just set these null values to 0.0 because of how the model is trained (since not all the dates are null, so setting some to zero would be misrepresenting the particular sample the the model). So how can I fix this or what can I put in the place of a null where a Double is expected?
Thanks for the advice :)
Here is what I do to the date Strings before I row.put("date_field", "<date string>") some <date string> into a RowData object (see here) that EasyPredictModelWrapper can predict on:
/**
*
* #param str_date (in MM/dd/yyyy form)
* #return string representation of timestamp value, either the string value of the str_date timestamp or "NULL"
* if can parse str_date to Date object, else returns null
*/
private String dateString2TimestampString(String str_date) {
if (str_date.toUpperCase().equals("NULL")) {
return "NULL";
} else {
try {
// convert date (MM/DD/YYYY) string to java date
DateFormat formatter;
formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = (Date) formatter.parse(str_date);
// convert date string to timestamp (since epoch time) (double??)
double epochTimestamp = (double) date.getTime();
return new BigDecimal(epochTimestamp).toPlainString();
} catch (Exception e) {
System.out.println("** dateString2TimestampString: could not parse string \"" + str_date + "\" to Date object");
System.out.println(e.getClass().getCanonicalName());
System.err.println(e.getMessage());
System.exit(1);
return null;
}
}
}
Be sure to set the convertInvalidNumberToNa config (see near the top of this code) for the wrapper as well so that is nicely handles "NULL" strings. E.g.:
EasyPredictModelWrapper model = new EasyPredictModelWrapper(
new EasyPredictModelWrapper.Config()
.setModel(MojoModel.load(MODEL_CLASS_NAME))
.setConvertUnknownCategoricalLevelsToNa(true)
.setConvertInvalidNumbersToNa(true)
);
How can i can reset the transactions number from ONE if new month is come.. for example, last entry is 17020005 become 17030001. The code is working but not reset transaction number from one when new month is come.
The code which i am using is
public void new(){
Date date =new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyMM");
String time = sdf.format(date);
try{
Connection con = new Connection ();
con.openConnection();
con.statement = con.dbConnection.createStatement();
ResultSet rs = con.statement.executeQuery("select right(id_sell,4) as id from sell");
if (rs.first()==false){
txtId.setText(time+"0001");
}
else
{
rs.last();
int no = rs.getInt(1)+1;
String cno = String.valueOf(no);
int pjg_cno = cno.length();
for (int i=0;i<4-pjg_cno;i++){
cno = "0"+cno;
}
txtId.setText(time+cno);
}
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Fail!");
}
}
As Henry suggests, it looks like your "id_sell" values are made up of the year, month and a unique integer - if so, you could change your SQL query to include a WHERE clause to match the first four digits of your time string - WHERE id_sell LIKE '1703%'.
However, long term (and assuming you control the DB structure), I'd suggest thinking about storing those values separately - if you had a month field and a transaction_id field it would be much easier and more efficient to query this data.
I'd also suggest thinking about whether you could generate IDs on the database using a sequence - it's hard for this java code to guarantee uniqueness and raises potential concurrency issues.
Have file name pattern as YYYYMDD or YYYYMMDD as below.
Have list of files with below pattern in a directory.
Have to read the latest file based on the file name in java.
How to do this?
xxx_2016103
....
xxx_20161104
If you have your filenames in a list, you can create a custom comparator to sort the list based on the date in the filename.
public class FilenamesWithDateSuffixComparator implements Comparator<String> {
private static final int ONE_DIGIT_MONTH_FORMAT = "yyyyMdd".length();
#Override
public int compare(String o1, String o2) {
String date1 = o1.substring(o1.lastIndexOf("_") + 1);
String date2 = o2.substring(o2.lastIndexOf("_") + 1);
// If the dates only have one digit for the month, insert a zero.
if (date1.length() == ONE_DIGIT_MONTH_FORMAT) {
date1 = date1.substring(0, 4) + "0" + date1.substring(5);
}
if (date2.length() == ONE_DIGIT_MONTH_FORMAT) {
date2 = date2.substring(0, 4) + "0" + date2.substring(5);
}
return date1.compareTo(date2);
}
}
Then, you can sort the list using the comparator:
Collections.sort(fileNamesList, new FilenamesWithDateSuffixComparator());
Or using the list short method in Java 8:
fileNamesList.sort(new FilenamesWithDateSuffixComparator());
Best solution is to fetch the dates, map them to files, and let the fact that TreeMap objects implement SortedMap so they are ordered do the work for you.
Map<Date,File> filedatemap = new TreeMap<Date,File>();
for(File f : inputdir.listFiles()) { //Assumption: inputdir is a File object pointing to the target directory.
String filename = f.getName();
DateFormat df = new SimpleDateFormat("YYYYMMdd");
Date filedate = df.parse(filename, new ParsePosition(filename.getLastIndexOf('_'));
filedatemap.put(filedate,f);
}
File latestfile = filedatemap.lastEntry().getValue(); //Last entry because natural order of Date is chronological.
//Go do things with that file
For best results, take Zircon's comment to heart and pad your single digit Months/Days with 0 so that that SimpleDateFormat will parse correctly.
Create a small class FileDateWrapper containing String filename; DateTime date;
Collect all the filenames in a List<FileDateWrapper> (leave date null for now)
Use some date/time API like Joda or java.time (Java 8 +) to create two date formats (as you have described)
Go through the list, striping off the _ character (.split()) and then attempting to parse the resulting string on both formats (eg. using parseDateTime(String). Store the date that was succesfully parsed in the field of your FileDateWrapper
Implement Comparator or Comparable and sort your list of FileDateWrapper (or Collections.max)
This question already has answers here:
SimpleDateFormat.parse() ignores the number of characters in pattern
(5 answers)
Closed 7 years ago.
I am working on a project where I need to validate multiple dates based on length and patterns. I am using simple date format and found many issues with that. My requirement is to strictly allow if date string matches "yyyy/MM/dd" and strictly 10 characters.
The below code is not giving expected results for various testing input strings.
public static boolean checkformat(String dateString){
boolean flag = false;
Date d1 = null;
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
format.setLenient(false);
try {
d1 = format.parse(dateString);
flag=true;
} catch (ParseException ex) {
ex.printStackTrace();
return false;
}
return flag;
}
the above code is returning "true" for various inputs like "99/03/1" (should be 0099/03/01) and 99/1/1( should be 0099/01/1). Since the input strings are not coming from a from so I cant perform validations before passing them to this method. Please suggest any implementation which should act very strict towards the dateformat("yyyy/MM/dd").
I suggest that you should try to validate date with regex before format it.
user below code for validate
public static boolean checkformat(String dateString){
boolean flag = false;
Date d1 = null;
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
format.setLenient(false);
try {
if (dateString.matches("([0-9]{4})/([0-9]{2})/([0-9]{2})")) { // use this regex
d1 = format.parse(dateString);
flag=true;
}
} catch (ParseException ex) {
ex.printStackTrace();
return false;
}
return flag;
}
Okay, first: You know what format you're expection. So why just parse it and catch an exception rather than checking preconditions ?
if(dateString.size() > 10) {
...
What you are actually doing is not checking your input format but rather parsing it - though the method is not expressing this contract -
so if your method is just for checking you could:
1. Use a regex
2. ... ?
I know that are quiet a lot of answers on the net which propose using SimpleDateFormat, but - to be frank -they are wrong.
If I am expecting a given format, e.g. as I know that conversions have been made on some user input, I can start parsing a string, and considering that something may have gone wrong, catch the exception. If I don't know which format is passed to me, I am at the validation layer and this layer should not try to perform a conversion but rather proof that the conversion would be valid.
You could try using the new java.time package from Java 8 and later. You could use it as so to replace the SimpleDateFormat:
public static boolean checkformat(String dateString){
boolean flag = false;
try {
TemporalAccessor ta = DateTimeFormatter.ofPattern("yyyyMMdd").parse(strDate);
flag=true;
} catch (DateTimeParseException ex) {
ex.printStackTrace();
return false;
}
return flag;
}
This would also limit the values from making no sense (e.g. month value being 18).
String[] removeSlashes=new String[3];
removeSlashes = enteredDate.split("/");
if(removeSlashes[0].length()!=4)
throw new IncorrectDateFormatException(); // user defined exception
if(removeSlashes[1].length()!=2)
throw new IncorrectDateFormatException();
if(removeSlashes[2].length()!=2)
throw new IncorrectDateFormatException();
//Then use SimpleDateFormat to verify
I have a swing form which includes jXDatePicker to capture dates. When a date is not selected in the jXDatePicker an error is thrown when the trying to inserting the date into the database. Below is the error I am getting in Netbeans:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
Below is the code that is giving me errors:
String dateOpened, dateOfLastUpdate, dateOf1stDelinquency, dateOfLastPayment, dateClosed;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
dateOpened = format.format(jXDatePicker7.getDate());
dateOfLastUpdate = format.format(jXDatePicker2.getDate());
dateOf1stDelinquency = format.format(jXDatePicker4.getDate());
dateOfLastPayment = format.format(jXDatePicker5.getDate());
dateClosed = format.format(jXDatePicker6.getDate());
String query2 = "insert into ACCOUNT (ACCOUNT_NUMBER,DATE_CLOSED ,DELINQUENCY_DATE, UPDATE_DATE,AMOUNT_OWING,"
+ "BALANCE,PAYMENT_HISTORY,ACCOUNT_STATUS,MONTHLY_PAYMENT,TERMS_DURATION,PRINCIPAL,CREDIT_LIMIT,"
+ "DATE_OPENED,PORTIFOLIO_TYPE,ACCOUNT_TYPE,NATIONAL_ID,COSIGNER_NATIONAL_ID)"
+ "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement preparedStatement2 = con.prepareStatement(query2);
preparedStatement2.setString(1, acc_no);
preparedStatement2.setString(2, dateClosed);
preparedStatement2.setString(3, dateOf1stDelinquency);
preparedStatement2.setString(4, dateOfLastUpdate);
preparedStatement2.setDouble(5, amount_owing);
preparedStatement2.setDouble(6, current_balance);
preparedStatement2.setString(7, payment_history);
preparedStatement2.setString(8, account_status);
preparedStatement2.setDouble(9, monthly_payment);
preparedStatement2.setDouble(10, terms_duration);
preparedStatement2.setDouble(11, principal);
preparedStatement2.setDouble(12, credit_limit);
preparedStatement2.setString(13, dateOpened);
preparedStatement2.setString(14, portfolio_type);
preparedStatement2.setString(15, acc_type);
preparedStatement2.setString(16, national_id);
preparedStatement2.setString(17, cosigner_national_id);
preparedStatement2.executeUpdate();
Some dates are not required and applicable on some instances, therefore the user cannot select a date under such circumstances.
Check each individual JXDatePicker's date like jXDatePicker2.getDate() for null. Do not call format.format if that date does happen to be null. I get that exact same error you mentioned on the format.format line if the date is empty and enter is pushed. Instead, go for some default time, like new Date(0); meaning:
format.format(new Date(0));
Use following code and make sure that dateOpened column in database accept NULL values.
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if(jXDatePicker7.getDate() != null){
dateOpened = format.format(jXDatePicker7.getDate());
}else{
dateOpened = null;
}
If you don't want to insert NULL value then show error message as
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if(jXDatePicker7.getDate() != null){
dateOpened = format.format(jXDatePicker7.getDate());
}else{
//error
}