How to fix exception java.lang.StringIndexOutOfBoundsException? - java

Here is my code:
public VerifyTopicNotificationPage timeOfReceivedTopic()
{
Date objDate = new Date(); // Current System Date and time is assigned to objDate
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("E, MM dd, yyyy hh:mm");
String dateString = sdf.format(objDate);
System.out.println("Date in the format : "+dateString);
Date dateObject = new Date();
System.out.println("Syshour is : " + objDate.getHours() + " " + "SysMin is : " + objDate.getMinutes());
//try for notification
int counter=0;
Boolean flag=false;
while((counter<10)&&(!flag)) {
driver.navigate().refresh();
seleniumUtil.explicitWait(2000);
seleniumUtil.clickElement(clickOnBellIcon);
seleniumUtil.explicitWait(4000);
String s1="";
String s2="";
try {
s1 = (driver.findElement(By.xpath("/html/body/div[3]/div/div/div/div[2]/div[2]/span")).getText())+(" ");
s2 = s1.substring(0, 26).trim();
System.out.println("Substring is " + s2);
SimpleDateFormat format2 = new SimpleDateFormat("EEE, MMM dd, yyyy hh:mm a", Locale.US);
Date date1 = null;
try {
date1 = format2.parse(s2);
System.out.println("UI Date is : " + date1);
System.out.println("UI hour is : " + date1.getHours());
System.out.println("UI min is : " + date1.getMinutes());
} catch (ParseException e) {
e.printStackTrace();
}
if ((dateObject.getHours()==(date1.getHours())))
{
if (((dateObject.getMinutes() <= date1.getMinutes()) && (dateObject.getMinutes() <= dateObject.getMinutes()+10)) || ((dateObject.getMinutes() >= date1.getMinutes()) && (dateObject.getMinutes() >= dateObject.getMinutes()+10))) //3.55 -> 4.03 | 3.58
{
System.out.println("Match found at " + s2);
flag = true;
break;
}
}
}
catch(Exception e)
{
System.out.println("encountered exception " + e);
}
counter++;
seleniumUtil.explicitWait(60000);
}
Assert.assertTrue(flag);
return PageFactory.initElements(driver, VerifyTopicNotificationPage.class);
}
Result of my code:
Date in the format : Tue, 02 02, 2021 09:45
Syshour is : 9 SysMin is : 45
encountered exception java.lang.StringIndexOutOfBoundsException: String index out of range: 26
I tried using trim() method but still it gives me the same exception.
How to resolve it?

s2 = s1.substring(0, 26).trim();
This happens if the length of s1 is less than 26. First, you need to check the length of the s1 and then you can apply the substring() method based on the length of s1.

Related

Convert a String of 6 into mm/dd/yyyy h:m with conditions

I'm developing an API in which one of the object should satisfy the below:
I've a column in Postgress DB as :
input = 201800
Input(column -datatype is character[6]) 201801
.
.
.
201812
Requirement :
Check if the input is current year
check if the last 2 digits are zeros , then ignore
if it is 201802 : dd=01(always), 02(Month) and 2018(year)
after checking the conditions, if it satisfies display like this :
For Ex: input = 201803 then o/p should in MM/DD/YYYY h:m format
Always month is 01 for month in between (01-12),O/P = 01/03/2018 12:00
I tried this, but didn't gibe O/P as per ,y requirement:
public class sample {
public static void main(String[] args) {
try {
String input= "201700" + "00";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
Date d = sdf1.parse(input);
System.out.print(d);
String formateDate = new SimpleDateFormat("MM/dd/yyyy hh:mm").format(d);
System.out.print(formateDate);
} catch(Exception e) {}
}
}
Appreciate your help!
I created a method mapDate() that is actually verifying your condition and return the wanted output. You just have to pass the value as parameter to the method. See the example below:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) {
String result1 = mapDate("201802"+"00");
System.out.print("result: " + result1 + "\n");
String result2 = mapDate("201702"+"02");
System.out.print("result: " + result2 + "\n");
String result3 = mapDate("201802"+"02");
System.out.print("result: " + result3);
}
public static String mapDate(String value){
String myDate;
myDate = "";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy");
String thisYear = format1.format(new Date());
if(!value.substring(value.length() - 2).equals("00") && value.substring(0, 4).equals(thisYear))
myDate = "01/" + value.substring(4, 6) + "/" + value.substring(0, 4) + " 12:00";
return myDate;
}
}
The ouput of this example is:
result:
result:
result: 01/02/2018 12:00

Parameter index out of range (3 > number of parameters, which is 2) error

I get the following error when I try to talk to my SQL database.This method gets two string values from a JSP page. The code gets this weeks dates set by the first int.
However, the problem is when I'm trying to talk to the database. It must be a syntax error. I've tried using different brackets
public String getSpecificSpot(String day, String hour) {
String result = "";
int dayNo= Integer.parseInt(day);
Calendar cal = GregorianCalendar.getInstance();
//System.out.println("Current week = " + Calendar.DAY_OF_WEEK);
// Set the calendar to monday of the current week
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Current week = " + Calendar.DAY_OF_WEEK);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String monday = "";
monday = df.format(cal.getTime());
//System.out.println(monday);
cal.add(Calendar.DATE, dayNo);
String currentDay = df.format(cal.getTime());
String currentDay2= currentDay;
System.out.println("Current DAY: "+currentDay);
boolean found = false;
Connection c = DBHelperClass.getConnection();
String query = "Select * from timetableslot WHERE date BETWEEN ? 00:00:00.00' AND ? 23:59:59.999' and time= ? ";
if (c != null) {
try {
PreparedStatement inserter = c.prepareStatement(query);
inserter.setString(1, currentDay);
inserter.setString(2, currentDay2);
inserter.setString(3, hour);
System.out.println("validating user: " + query);
ResultSet resultSet = inserter.executeQuery();
while (resultSet.next()) {
//result = resultSet.getInt("classID");
result= String.valueOf(resultSet.getInt("slotID"));
System.out.println(result+" result value");
found = true;
}
} catch (SQLException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
}
}
//result="ssa";
return result;
}
The error that I get is:
java.sql.SQLException: Parameter index out of range (3 > number of parameters, which is 2).
Hi I have fixed it just after posting the question
public String getSpecificSpot(String day, String hour) {
String result = "";
int dayNo= Integer.parseInt(day);
Calendar cal = GregorianCalendar.getInstance();
//System.out.println("Current week = " + Calendar.DAY_OF_WEEK);
// Set the calendar to monday of the current week
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Current week = " + Calendar.DAY_OF_WEEK);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String monday = "";
monday = df.format(cal.getTime());
//System.out.println(monday);
cal.add(Calendar.DATE, dayNo);
String currentDay = df.format(cal.getTime());
String currentDay2= currentDay;
System.out.println("Current DAY: "+currentDay);
boolean found = false;
Connection c = DBHelperClass.getConnection();
String query = "Select * from timetableslot WHERE date BETWEEN ? AND ? and time= ? ";
if (c != null) {
try {
PreparedStatement inserter = c.prepareStatement(query);
inserter.setString(1, currentDay + " 00:00:00.00");
inserter.setString(2, currentDay2+ " 23:59:59.999");
inserter.setString(3, hour);
System.out.println("validating user: " + query);
ResultSet resultSet = inserter.executeQuery();
while (resultSet.next()) {
//result = resultSet.getInt("classID");
result= String.valueOf(resultSet.getInt("slotID"));
System.out.println(result+" result value");
found = true;
}
} catch (SQLException ex) {
Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
}
}
//result="ssa";
return result;
}

Operator '<' cannot be applied to 'java.lang.String'

i got the system time in a string for example something like "1240".
then i wanted to do something like if the system time was < than 1240,then close the application.
but it gives me the "Operator '<' cannot be applied to java.lang.String!" Error!
My code is :
runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime= (TextView)findViewById(R.id.showtime);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int mynum = 1240;
String curTime = hours + "" + minutes;
txtCurrentTime.setText(curTime);
if(curTime < mynum ){
System.exit(0);
}
}catch (Exception e) {}
}
});
What's the problem?
try{
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String str1 = String.valueOf(hours1) + ":" + String.valueOf(minutes1) + ":" + "00";
String str2 = String.valueOf(hours2) + ":" + String.valueOf(minutes2) + ":" + "00";
Date date1 = formatter.parse(str1);
Date date2 = formatter.parse(str2);
if (date1.compareTo(date2)<0)
{
// if date2 > date1
}
}catch (ParseException e1){
e1.printStackTrace();
}
formats for dates
check date/time format as per your requirement from here
< is not defined for a string and an int of course . So you can't use it .
your current time can be calculated like this :
int curTime = 100*hours + minutes;
then you can use < between two integers.
I believe though you must use System Milliseconds which is more usual.
if(hours * 100 + minutes < mynum){
System.exit(0);
}

How to Compare datetime in Android

I have dates, date1(now) and date2 which is returned in a JSON string say 2016-07-09 21:26:04.
I want to compare those two dates something like
if(date1 < date2){
}
Here is the code to compare two DateTime objects in Android:
public void onDateSelected(DateTime dateSelected) {
DateTime currentDateTime = new DateTime();
try{
// You can use any format to compare by spliting the dateTime
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ");
String str1 = dateSelected.toString();
Date selectedDate = formatter.parse(str1);
String str2 = currentDateTime.toString();
Date currentDate = formatter.parse(str2);
if (selectedDate.compareTo(currentDate)<0)
{
System.out.println("current date is Greater than my selected date");
}
else
{
System.out.println("selected date is Greater than my current date");
}
}catch (ParseException e1){
e1.printStackTrace();
}
}
I would do this:
parse the in to Date objects
compare those
Example:
public static void main(String x[]) throws ParseException {
String s1 = "2016-07-09 21:26:04";
String s2 = "2006-07-09 21:26:04";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = sdf.parse(s1);
Date d2 = sdf.parse(s2);
int compareResult = d1.compareTo(d2);
if (compareResult > 0) {
System.out.println(s1 + " is younger than " + s2);
} else if (compareResult < 0) {
System.out.println(s1 + " is younger than " + s2);
} else {
System.out.println(s1 + " is equals than " + s2);
}
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date today= new Date();
try {
if (today.before(sdf.forrmat(json_string_date))) {
// If start date is before end date.
// Do your piece of code
}
}catch (ParseException e) {
e.printStackTrace();
}

java parse date time with milliseconds into date getting parse error

I have a string in which I am finding the datetime with milliseconds as follows:
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
String monthup = String.valueOf(month);
String dayup = String.valueOf(day);
String hourup = String.valueOf(hour);
String minuteup = String.valueOf(minute);
String secondup = String.valueOf(second);
String millisup = String.valueOf(millis);
if(monthup.length()==1){monthup="0"+monthup;}
if(dayup.length()==1){dayup="0"+dayup;}
if(hourup.length()==1){hourup="0"+hourup;}
if(minuteup.length()==1){minuteup="0"+minuteup;}
if(secondup.length()==1){secondup="0"+secondup;}
if(millisup.length()==1){millisup="0"+millisup;}
if(millisup.length()==2){secondup="00"+millisup;}
String timewithmilsec = year+ monthup + dayup+ hourup+ minuteup+ secondup+ millisup;
System.out.println(timewithmilsec);
I am getting a value: 20151020115216690 which is obviousely correct.
I want to parse it to java Date format.
What I did is as follows:
try{
DateFormat formatter = new SimpleDateFormat("yyyyMMdHHmmssaaa");
Date date = formatter.parse(timewithmilsec);
System.out.println(date);
}
catch(Exception e){
System.out.println(e);
}
I am getting an error as follows:
java.text.ParseException: Unparseable date: "20151020115247995"
You have only one d in your format, but are padding the day to two characters, also, according to the JavaDocs...
a Am/pm marker Text PM
which isn't a millisecond place holder, I think you mean SSS
For example...
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
String monthup = String.valueOf(month);
String dayup = String.valueOf(day);
String hourup = String.valueOf(hour);
String minuteup = String.valueOf(minute);
String secondup = String.valueOf(second);
String millisup = String.valueOf(millis);
if (monthup.length() == 1) {
monthup = "0" + monthup;
}
if (dayup.length() == 1) {
dayup = "0" + dayup;
}
if (hourup.length() == 1) {
hourup = "0" + hourup;
}
if (minuteup.length() == 1) {
minuteup = "0" + minuteup;
}
if (secondup.length() == 1) {
secondup = "0" + secondup;
}
if (millisup.length() == 1) {
millisup = "0" + millisup;
}
if (millisup.length() == 2) {
secondup = "00" + millisup;
}
String timewithmilsec = year + monthup + dayup + hourup + minuteup + secondup + millisup;
System.out.println(timewithmilsec);
try {
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Date date = formatter.parse(timewithmilsec);
System.out.println(date);
} catch (Exception e) {
System.out.println(e);
}
Which for me prints
20151020173034124
Tue Oct 20 17:30:34 EST 2015
And while I'm at it, let me introduce you to String.format, which can reduce all you int to String conversion and padding code down to...
String timewithmilsec = String.format("%04d%02d%02d%02d%02d%02d%03d", year, month, day, hour, minute, second, millis);
I am getting Tue Oct 20 12:04:08 IST 2015 but interestingly I did not see any millisecond here
Date#toString won't include the milliseconds by default, you will need to supply a DateFormat which can.
If I replace the last System.out.println with System.out.println(new SimpleDateFormat("dd MMM yyyy HH:mm:ss.SSS").format(date)); it prints something like
20 Oct 2015 17:37:14.856
(for the value 20151020173714856)
According to documentation letter S responds to milliseconds so your format should look like this new SimpleDateFormat("yyyyMMddHHmmssSSS"); (you have one d in your format).
The answer is the missing "d" in the date format, where #MadProgrammer depicts.
In addition, the generation of the string representation of the date should be reconsidered. You should use SimpleDateFormat.format() to generate date string as in the sample code below:
Calendar now = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String formattedDate = formatter.format(now.getTime());
System.out.println("Formatted date: " + formattedDate);
And the output will be in a format that you requested.
Formatted date: 20151020094934279

Categories