Formatting time from in java swing formatted text field - java

I'm new to java and I got this assignment to make a timer app with two options, "on time" and countdown" In both cases an app has to open a new window where colors are changing. I'm having problem with first option, for some reason I cant parse time to formatted text field.
I have tried several methods, sometimes it crashes and sometime it just starts working regardless of given time.
{
if (jCheckBox1.isSelected()){
st=true;
Object set = jFormatted.getText();
String setTime = new SimpleDateFormat("HH:mm:ss").format(set);
String appTime1 = new SimpleDateFormat("HH:mm:ss").format(appTime);
try
SimpleDateFormat form = new SimpleDateFormat("HH:mm:ss");
Date d1 = form.parse(setTime);
Date d2 = form.parse(appTime1);
razlika = d1.getTime() - d2.getTime();
catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}

Related

How to solve this error "String Cannot be converted to Date"?

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.

How can I save two or more data in same object[0]

I send date data (which comes from a CalendarView object) to the second activity.
This is the first activity:
String date = year + "/" + month + "/" + day;
intent=new Intent(Main3Activity.this,MainActivity.class);
intent.putExtra("date",date);
I get it by converting it to a timestamp in the second activity. So, I can choose a date and I can see it in the second activity, it works fine with 1 date. Here is the second activity:
// Create objects
Object[] item;
String s;
DateFormat formatter;
Date date2;
Timestamp timeStampDate;
List<Object[]> data;
long myTime;
myTime11 = sharedPreferences.getLong("long1",0);
s= getIntent().getStringExtra("date");
if(s != null) {
formatter = new SimpleDateFormat("yyyy/MM/dd");
try {
date2 = formatter.parse(s);
timeStampDate = new Timestamp((date2.getTime()));
myTime = timeStampDate.getTime();
editor.putLong("long1",myTime);
editor.commit();
} catch (ParseException e) {
e.printStackTrace();
}
item = new Object[COLUMN_NAMES.length];
item[0] = myTime11;
item[1] = 3;
item[2] = 6;
item[3] = 9;
data.add(item);
}
item = new Object[COLUMN_NAMES.length];
item[0] = timestamp;
item[1] = 0;
item[2] = 0;
item[3] = 0;
data.add(item);
cursor.addAll(data);
return item;
}
However, when I select a second date the first data disappears.
For example, I choose 13/09/2017. Okay, it passes but If I want to pass 14/09/2017 from the CalendarView object with the first activity again, then I can't see 13/09/2017. It changes to 14/09/2017 and I can only see one date which is 14/09/2017. How can I solve this?
Edit: I think it happens because of item[0] = myTime which is just one. If I add two like it, I can pass two dates side by side but I want this to work for all the dates that are selected.
Edit2: I use a library from GitHub. Most of my codes are similar to this: link. I have just changed specific details.
Edit3: When I added these to solve the problem thanks to suggestions, I get the these errors. How can I solve this?
data.add((Object[]) data.get(0)[0]);
data.add((Object[]) data.get(1)[0]);
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
data.add( 0, (Object[]) item[0]);
data.add( 1, (Object[]) item[0]);
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Object[]
You are adding the next time to an Object array called item, and then putting this in the List called data.
Depending on when data is created, this will cause the problem of the second (and third) date disappearing. If you create data as a private field in the code (before the second action runs). Like this:
// in the class file:
private List<Object[]> data = new ArrayList<Object[]>();
Then select a few dates with your code and the CalendarView object. Then use this in a new action / method when you want to get the dates:
public void printDates()
{
System.out.println(data.get(0)[0]); // gives the first date 2017/09/13
System.out.println(data.get(1)[0]); // gives the second date 2017/09/14
}
Or you can use this to get the specified date from the data List:
public Object getLastIthDate(int i)
{
return data.get(list.size() - i - 1);
}
Then somewhere else in the code:
System.out.println(getLastIthDate(1)); // gives the second last date that was saved: 2017/09/13
System.out.println(getLastIthDate(0)); // gives the last date that was saved: 2017/09/14
Edit: Solution to error from Edit3:
Just add the whole item object to data, like you had in the original code
data.add(item); then you will be able to use time = data.get(0)[0]; somewhere else in the code.

Java time manipulation - subtracting 2 strings

I am pulling 2 time values (as strings) from an XML file using xpath, these values (for example) are as follows:
00:07
08:00
00:07 is equal to 7 minutes
08:00 means 8am, with no date associated or needed (that is handled elsewhere)
Each of these values is subject to change in each XML file that i read. What i am attempting to do is as follows:
I need to subtract or add (depending on the situation) the 7mins from the 8am and give me a hh:mm time (eg: 07:53 or 08:07) in a string that i can eventually output to CSV
Next i need to produce 2 additional strings, 1 min before and 1 min after (eg: 07:52 and 07:54 OR 08:06 and 08:08) which also need to be output to CSV
I have tried everything and i can think of in relation to the time interpretation and manipulation to get the minutes subtracted/added to the time and then +/- 1 min from there, but being a complete novice i am totally stuck despite reading and testing as much as i could find. Spent the last 2 days working with Joda Time for the first time but i must be missing something fundamental as i cannot get the desired result with this either.
The question is - how can i achieve this?
Some sample code that gets me reading from the XML and printing the time
FileInputStream file = null;
try {
file = new FileInputStream(new File("Output/XmlConfig.xml"));
} catch (FileNotFoundException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
Document xmlDocument = null;
try {
xmlDocument = builder.parse(file);
} catch (SAXException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
XPath xPath = XPathFactory.newInstance().newXPath();
//get In Early rule from XML
String exceptionInEarlyXML = "Root/Response/WSAExceptionRule/#InEarly";
NodeList nodeListInEarly = null;
try {
nodeListInEarly = (NodeList) xPath.compile(exceptionInEarlyXML).evaluate(xmlDocument, XPathConstants.NODESET);
} catch (XPathExpressionException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
String exceptionInEarly = (nodeListInEarly.item(1).getFirstChild().getNodeValue());
String InEarly = exceptionInEarly;
SimpleDateFormat format = new SimpleDateFormat("hh:mm");
Date d2 = null;
try {
d2 = format.parse(InEarly);
} catch (ParseException ex) {
Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
}
DateTime dt2 = new DateTime(d2);
System.out.println(dt2);
This give me an output of 1970-01-01T00:07:00.000+10:00
I have tried so many permutations of code that i am at the point of deleting and starting again from scratch as it is un-compilable, and i am not experienced enough yet to be able to solve this issue.
Once you have the Date object for the parsed time, use getTime() to get the time in milliseconds and save it into a long variables. Then parse the offset time format and use a NumberFormat to get the number of minutes to offset. Add or subtract as needed. Take the result and create a new Date(millis) then apply your format to it.
Here is a working example:
String sTime = "08:00";
String sOffset ="00:07";
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");
Date dtTime = null;
try {
dtTime = dateFormat.parse(sTime);
} catch (ParseException e) {
// handle exception
return;
}
String[] offsetHrsMins = null;
NumberFormat numberFormat = NumberFormat.getNumberInstance();
long offsetMillis = 0;
try {
offsetHrsMins = sOffset.split(":");
long offsetHrs = (Long) numberFormat.parse(offsetHrsMins[0]);
long offsetMins = (Long) numberFormat.parse(offsetHrsMins[1]);
offsetMillis = 1000 * 60 * ((offsetHrs * 60) + offsetMins);
} catch (ParseException e) {
// handle exception
return;
}
long lTime = dtTime.getTime();
System.out.println("Adding minutes: " + dateFormat.format(new Date(lTime + offsetMillis)));
System.out.println("Subtracting minutes: " + dateFormat.format(new Date(lTime - offsetMillis)));
output:
Adding minutes: 08:07
Subtracting minutes: 07:53
First, you need to use SimpleDateFormat to parse the Date String to a Java.util.Date Object.
Second, After getting the Date Object, you can easily add/substract some time, and get another Date Object.
Last, you can use another SimpleDateFormat object to format the Date Object you got in second step to String.
SimpleDateFormat is very useful in Processing Date Strings. You can refer to the Javadoc in JDK or search some examples by Google.
Try passing the strings into a method aswel as what you are subrtacting by
Then converting them to ints
Then have an if statment that if the subtraction amount is greater that the minets int
then it subtracts 1 from the hours int and sets the new minets int to 60 subtract the subtraction int
Then convert them back to Strings
Here is the code exept for turing it back into a string
public class Main {
static String hours="8";
static String minets="7";
static String minus="17";
public static void main(String[] args) {
Main m = new Main();
m.timechange(hours,minets,minus);
}
void timechange(String hour, String minuet, String subtract){
int h = Integer.parseInt(hour);
int m = Integer.parseInt(minuet);
int s = Integer.parseInt(subtract);
if(s>m){
h-=1;
m=60-s;
}
else{
m-=s;
}
if ((m>9)&&(h>9)) {
System.out.println(h+":"+m);
} else {if ((m<10)&&(h<10)) {
System.out.println("0"+h+":0"+m);
}else {if ((m<10)&&(h>9)) {
System.out.println(h+":0"+m);
}else {if ((m>9)&&(h<10)) {
System.out.println("0"+h+":"+m);
}
}
}
}
}}
I wasnt sure if you wanted the back to String.
Hopeful that answers your question
The same can be done for when the minets reach over 60 if that ever happens.
Here a genuine Joda-Time answer because OP wants Joda-Time (and I also consider that library as superior to java.util.Date, java.text.SimpleDateFormat etc.):
Joda-Time has the big advantage of having several different temporal types. The right type for handling plain wall times is LocalTime. It also defines a method to add minutes.
Your task:
I need to subtract or add (depending on the situation) the 7mins from the 8am and give me a hh:mm time (eg: 07:53 or 08:07) in a string that i can eventually output to CSV
Next i need to produce 2 additional strings, 1 min before and 1 min after (eg: 07:52 and 07:54 OR 08:06 and 08:08) which also need to be output to CSV
The solution (only for part one, the other part is very similar):
LocalTime time = new LocalTime(8, 0); // corresponds to 08:00
LocalTime laterBy8Minutes = time.plusMinutes(7);
LocalTime earlierBy8Minutes = time.minusMinutes(7);
String sLaterBy8Minutes = laterBy8Minutes.toString("HH:mm"); // 08:07
String sEarlierBy8Minutes = earlierBy8Minutes.toString("HH:mm"); // 07:53
One additional note: If you start with another type like java.util.Date and wish to convert it to LocalTime then you can use the constructor
new LocalTime(jdkDate, DateTimeZone.forID("Europe/Moscow")) // example
or for default timezone:
new LocalTime(jdkDate)

Converting items inside ArrayList to different types

I have a part inside my program where the user logs into have access to the application, when the user logs in I have a time stamp being taken and stored into an ArrayList. When the user logs out I have another time stamp taken for when they logged out. I have been trying to subtract the 2 times from each other, but it is not allowing me to. They are stored in a String ArrayList, I am aware you can't subtract String, so I have tried converting to double, int, date, etc... None of it works for me. My question is that I would like the difference between the two times. I am also aware that there are other question similar to this on SO, but none specific to this exact question, that is why I posted it. I am not trying to post a duplicate.
Code:
loginButton.addActionListener(
new ActionListener()
{
//method for events that will be performed when 'loginButton' is pressed
public void actionPerformed(ActionEvent e)
{
try
{
//gets texts from specified text fields and assigns to instance variable
String userNameFromLogin = userNameTextBox.getText().trim();
String password = passwordTextBox.getText().trim();
//instance variable and object that holds currrent time when logged in
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm");
Date date = new Date();
String loginTime = dateFormat.format(date);
//sql statement that check if username and password exist
String sql5 = "SELECT User_name,Password FROM Employee_Table WHERE User_name = '" + userNameFromLogin + "' and Password = '" + password + "'";
//execute query, assigning all records in db to 'rs5'
rs5 = st.executeQuery(sql5);
//instance variables
int count = 0;
//loops until reaches end up 'rs5'
while(rs5.next())
{
count++;
}
//statement and actions if 'userName' and 'password' match
if(count == 1)
{
//sets 'welcomeFrame' to true
welcomeFrame.setVisible(true);
//sets 'loginFrame' to false
loginFrame.setVisible(false);
//sets text fields to blank
userNameTextBox.setText("");
passwordTextBox.setText("");
//adds 'userNameFromLogin' to array
loginArray.add(userNameFromLogin);
//adds 'loginTime' to array
loginArray.add(loginTime);
//sets label to current username logged in
userNameLabel.setText("logged in as: " + userNameFromLogin);
}
//statement and actions if 'userName' and 'password' do not match
else
{
JOptionPane.showMessageDialog(null, "Username or password incorrect!");
userNameTextBox.setText("");
passwordTextBox.setText("");
}
}
catch(Exception ex)
{
}
}
});
}
logoutHomeButton.addActionListener(
new ActionListener()
{
//method for events that will be performed when 'employeeFormButton' is pressed
public void actionPerformed(ActionEvent e)
{
try
{
//instance variable and object that holds currrent time when logged in
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm");
Date date = new Date();
String logoutTime = dateFormat.format(date);
//sets 'loginFrame' to visible
loginFrame.setVisible(true);
//sets 'welcomeFrame' to not visible
welcomeFrame.setVisible(false);
//adds 'logoutTime' to array
loginArray.add(logoutTime);
//statement that selects everything from our 'Login_Info'
String sql7 = "SELECT * FROM Login_Info";
//execute query, assigning all records in db to 'rs7'
rs7 = st.executeQuery(sql7);
//moves cursor to next row
rs7.moveToInsertRow();
//inserts record into db
rs7.updateString("User_Name", loginArray.get(0));
rs7.updateString("Login_Time", loginArray.get(1));
rs7.updateString("Logout_Time", loginArray.get(2));
//inserts data into db
rs7.insertRow();
JOptionPane.showMessageDialog(null, "You have successfully logged out!");
}
catch(Exception ex)
{
}
}
});
}
The ArrayList is a global variable at the top of my program. The two variable names I will be subtracting are loginTime and logoutTime and their respected indexes inside the ArrayList.
Thanks for any guidance
You can convert the strings back to dates using your SimpleDateFormat.parse(). Once they are both in Date format:
long elapsed = logoutDate.getTime() - loginDate.getTime(); // Elapsed time in ms

How do i handle an empty jXDatePicker?

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
}

Categories

Resources