I am unable to loop through my database for timeList to output different time that I require. They only loop through the first one and display the same data for every output that I require. If I were to close the for loop of of the conversion, I would have problem displaying it in the output statement.
String[] timeMinute = timeList .split("<SPLIT>");
for (int t = 0; t <timeMinute.length; t ++)
{
String strDate = timeList;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date getDate = sdf.parse(strDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(getDate);
int noOfHours = calendar.get(Calendar.HOUR_OF_DAY);
int noOfMinutes = calendar.get(Calendar.MINUTE);
int totalMinutes = noOfHours * 60 + noOfMinutes;
while ( rs.next() )
{
String RTD= rs.getString("RTD");
if ( !trd1.contains( RTD) )
trd1.add(RTD);
String admissionCOUNT = "";
if ( rs.getString("jae") != null )
admission = rs.getString("jae");
String[] admissionCOUNT = admission.split("<SPLIT>");
for ( int i = 0 ; i <gateNo.length ; i ++ )
{
if ( kpm.containsKey(gateNo[i]) )
kpm.get(admissionCOUNT [i]).put(RTD, + totalMinutes);
}
}
for ( int i = 0 ; i < .size(); i++)
{
stringWriter.append( trd1.get(i) + ",");
for ( String admissionCOUNT : kpm.keySet() )
{
if ( kpm.get(admissionCOUNT ).containsKey(trd1.get(i) ) )
MSO.get(admissionCOUNT ).append(totalMinutes +",");
else
MSO.get(admissionCOUNT ).append("0,");
}
}
The current output example -
data1,0,56,0
data2,56,0,0
data3,56,0,0
data4,0,0,56
Desire output example -
data1,0,87,0
data2,56,0,0
data3,43,0,0
data4,0,0,91
edit:
for ( String egm : .keySet() )
resultString += System.getProperty("line.separator") + gate + "," + MSO.get(egm).toString();
Related
I want to set text by date and incrementing loop, and when the day changes looping start from the beginning.
Example
1. day 1 =
a. nameFile 110920190001
b. nameFile 110920190002, etc.
2. day 2 =
a. nameFile 120920190001
b. nameFile 120920190002, etc.
Code
Date documentsDate = Calendar.getInstance().getTime();
SimpleDateFormat documentDates = new SimpleDateFormat("ddMMyy");
String setTitleDocument = documentDates.format(documentsDate);
for(int i = 1; i <= 1000; i++) {
String countDocument = String.format("%04d", i);
textNameDocument.setText("Document " + setTitleDocument + countDocument);
}
Just put the Date Initialization in the for loop for it to always take the new Instance of the date.
public static void replace(String s) {
for (int i = 1; i <= 1000; i++) {
Date documentsDate = Calendar.getInstance().getTime();
SimpleDateFormat documentDates = new SimpleDateFormat("ddMMyy");
String setTitleDocument = documentDates.format(documentsDate);
String countDocument = String.format("%04d", i);
textNameDocument.setText("Document " + setTitleDocument + countDocument);
}
}
I use the code below to see if my input date (format mm/dd/yyyy HH:mm:ss) falls within the range of startDate and endDate.
I use compareTo() in this logic. But with the format mm/dd/yyyy, it compares the month alone and prints output in "MYLOGIC methood". But I need the year to be compared to see if the input date is within startDate and endDate range.
public class DateLogicNew {
public static void main(String[] args) {
String startDate[] = new String[1];
String endDate[] = new String[1];
startDate[0] = "01/01/0600 00:00:00";
endDate[0] = "11/27/3337 00:00:00";
String inputArr[] = { "05/01/0500 01:00:00", "11/27/3337 00:00:00",
"05/05/0700 00:00:00", "11/27/2337 00:00:00",
"06/05/4000 00:00:00" };
String protectedArr[] = new String[inputArr.length];
int temp[] = new int[inputArr.length];
System.out.println(inputArr.length);
System.out.println("Length of the inputArr: " + inputArr.length);
// System.out.println("");
for (int i = 0; i < inputArr.length; i++) {
if (inputArr[i]
.matches("^([0-1][0-9])/([0-3][0-9])/([0-9]{4})(?:( [0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$")) {
System.out.println("Inside if loop");
if (inputArr[i].compareTo(startDate[0]) > 0
&& inputArr[i].compareTo(endDate[0]) < 0) {
System.out.println("inside the compare condition");
temp[i] = 1;
protectedArr[i] = inputArr[i];
System.out
.println("Values of the inputArr in MYLOGIC method : "
+ protectedArr[i]);
}
} else {
temp[i] = 0;
}
}
System.out.println("");
for (int i = 0; i < inputArr.length; i++) {
if (temp[i] == 1) {
inputArr[i] = protectedArr[i];
}
System.out
.println("Final Value to the output port: " + inputArr[i]);
}
}
}
java.time
Parse as date-time objects. Regex is overkill.
The modern approach uses the java.time classes rather than the old legacy date-time classes.
String input = "05/01/0500 01:00:00" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
Compare using methods isBefore, isAfter, isEqual.
if( ( ! x.isBefore( start ) ) && x.isBefore( stop ) ) { … }
I myself figured out the solution for my question. Please check the code below to see the logic before comparing the dates.
String startDate = "0600/01/01 00:00:00";
String endDate = "3337/11/27 00:00:00";
try {
for (int i = 0; i < inputArr.length; i++) {
String newDateInput = inputArr[i];
// System.out.println("NewInput:" + newInput);
DateFormat parser = new SimpleDateFormat("MM/dd/yyyy");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date convertedDate = parser.parse(newDateInput);
String newFormattedInput = formatter.format(convertedDate);
// System.out.println("newFormattedInput: " +
// newFormattedInput);
if (newFormattedInput
.matches("^([0-9]{4})/([0-1][0-9])/([0-3][0-9])(?:( [0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$")) {
if (newFormattedInput.compareTo(startDate) > 0
&& newFormattedInput.compareTo(endDate) < 0) {
temp[i] = 1;
protectedArr[i] = inputArr[i];
System.out
.println("Values of the inputArr in PROTECT method : "
+ protectedArr[i]);
} else {
temp[i] = 0;
}
}
}
} catch (ParseException e) {
e.printStackTrace();
}
I am trying to write a simple query that contains a group by and a where clause in greendao however I am getting an error when I add in the where clause . Is there another way to write the where clause so that I can get this to work
I am basically getting the day part of today and subtracting 1 so that I can upload data from the previous day.
public List<AppTimeUsage> LoadAppTimeUsageData() {
List<AppTimeUsage> items = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
int thisDay = calendar.get(Calendar.DAY_OF_MONTH);
int previousDayCheck = thisDay -1 ;
String sqlWhere;
sqlWhere = "WHERE DAY_RECORDED = " + previousDayCheck;
String sql = "SELECT APP_NAME , SUM(APP_TIME_SPENT) , DAY_RECORDED FROM APP_TIME_USAGE " + sqlWhere + " GROUP BY APP_NAME ; ";
Cursor c = appTimeUsageDao.getDatabase().rawQuery(sql, null);
int offset = 0;
int d;
int cd;
String e = "";
while (c.moveToNext()) {
AppTimeUsage atu = new AppTimeUsage(
Long.MIN_VALUE,
new Date(),
c.getInt(1),
c.getString(0),
c.getInt(2)
// break;
);
items.add(atu);
//stats = atu;
}
return items;
}
I'm trying to optmize a query executed on a Java program at work.
We have to generate a huge ammount of data to test a program and it is taking 2~3 hours for the query to be executed.
Today, the program create a "SELECT" line for each data that we have previously stored on an ArrayList.
I'm trying to create a query with an IN clause with 1000 parameters inside of it.
I have already searched for some other examples here, but the error that I'm getting now is different from everything that I have found until now.
The query string was created perfectly, with 1000 "?" and I have set 1000 parameters with a "for", as you can see on the code.
But when I execute the query, my ResultSet object return with only 1 row, instead of the 1000 rows that I have on my database.
The code here is an adaptation from the code that I have at work, I can't post the original because of confidential reasons.
At work is an Oracle environment and at my home is a MySQL environment.
Hope that I explained in a way that someone can help me!
Thanks in advance!
public ArrayList<String> getDadosIn(ArrayList<String> lista)
{
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList< String > listaDados = new ArrayList< String >();
Connection conn = ConnectionUtil.getDBConnection();
try
{
StringBuilder query = new StringBuilder();
Calendar calendar = Calendar.getInstance();
NumberFormat numberFormat = new DecimalFormat( "00" );
System.out.println( "Begin query: " +
numberFormat.format( calendar.get( Calendar.DAY_OF_MONTH ) ) + "/" + // Dia
numberFormat.format( calendar.get( Calendar.MONTH ) + 1 ) + "/" + // Mês
calendar.get( Calendar.YEAR ) + "-" + // Ano
numberFormat.format( calendar.get( Calendar.HOUR_OF_DAY ) ) + ":" + // Hora
numberFormat.format( calendar.get( Calendar.MINUTE ) ) + ":" + // Minuto
numberFormat.format( calendar.get( Calendar.SECOND ) ) ); // Segundo
query.append( "SELECT ID_CLIENTE FROM CLIENTE WHERE ID_CLIENTE IN (" );
int i = 1;
int countAux = 0;
int countElements = 0;
for ( int k = 0; k < lista.size(); k++ )
{
query.append( "?," );
countAux++;
countElements++;
if(countAux >= 1000)
{
query.deleteCharAt( query.length() - 1 );
query.append( ")" );
ps = conn.prepareStatement(String.valueOf( query ) );
for ( int j = 0; j < 1000; j++ )
{
ps.setInt( i++, Integer.parseInt(lista.get(countElements - 1)) );
}
rs = ps.executeQuery();
while ( rs.next() )
{
listaDados.add( rs.getString("id_cliente") );
}
ps.close();
query.delete( 0, query.length() );
query.append( "SELECT ID_CLIENTE FROM CLIENTE WHERE ID_CLIENTE IN (" );
i = 1;
countAux = 0;
System.out.println( "Registros selecionados: " + countElements + " - lista.size = " + listaDados.size());
}
}
// verifica se ainda há registros para selecionar, uma vez que os selects acima eram executados a cada N vezes
if(countAux > 0)
{
i = 1;
query.deleteCharAt( query.length() - 1 );
query.append( ")" );
ps = conn.prepareStatement(String.valueOf( query ) );
for ( int j = 0; j < 1000; j++ )
{
ps.setInt( i++, Integer.parseInt(lista.get(countElements - 1)) );
}
rs = ps.executeQuery();
while ( rs.next() )
{
listaDados.add( rs.getString("id_cliente") );
}
ps.close();
}
calendar = Calendar.getInstance();
System.out.println( "End query: " +
numberFormat.format( calendar.get( Calendar.DAY_OF_MONTH ) ) + "/" + // Dia
numberFormat.format( calendar.get( Calendar.MONTH ) + 1 ) + "/" + // Mês
calendar.get( Calendar.YEAR ) + "-" + // Ano
numberFormat.format( calendar.get( Calendar.HOUR_OF_DAY ) ) + ":" + // Hora
numberFormat.format( calendar.get( Calendar.MINUTE ) ) + ":" + // Minuto
numberFormat.format( calendar.get( Calendar.SECOND ) ) ); // Segundo
ps.close();
conn.close();
}
catch ( SQLException e )
{
e.printStackTrace();
}
return listaDados;
}
Couple of things :
In the for loop with Integer.parseInt(), the counter for lista.get(countElements - 1) needs to change to j :
for ( int j = 0; j < 1000; j++ )
{
ps.setInt( i++, Integer.parseInt(lista.get(countElements - 1)) );
}
Change to
for ( int j = 0; j < lista.size(); j++ )
{
ps.setInt( i++, Integer.parseInt(lista.get( j )) );
}
For all your for loops, use the lista.size() as the upper limit to avoid IndexOutOfBounds exceptions.
for ( int j = 0; j < lista.size(); j++ )
{
ps.setInt( i++, Integer.parseInt(lista.get( j )) );
}
I'm reading the data from CSV file. One of the fields is the time in the format H:mm, i.e. "8:00". How to convert this string value into the minutes (integer value), i.e. 8:00 = 8*60 = 480 minutes?
String csvFilename = "test.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] row = null;
csvReader.readNext(); // to skip the headers
int i = 0;
while((row = csvReader.readNext()) != null) {
int open = Integer.parseInt(row[0]);
}
csvReader.close();
You can use java.text.SimpleDateFormat to convert String to Date. And then java.util.Calendar to extract hours and minutes.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date date = sdf.parse("8:00");
cal.setTime(date);
int mins = cal.get(Calendar.HOUR)*60 + cal.get(Calendar.MINUTE);
Try something like this
String str = "8:10";
int minutes=0;
String[] arr= str.split(":");
if(arr.length==2){
minutes=Integer.parseInt(arr[0])*60+Integer.parseInt(arr[1]);
}
System.out.println(minutes);
Write something like this to convert into int
public int convertToMin(String hrmin) {
String[] tokens = hrmin.split(":");
int minutes = 0;
for (int i = tokens.length; i > 0; i--) {
int value = Integer.parseInt(tokens[i - 1]);
if (i == 1) {
minutes += 60 * value;
}
else {
minutes += value;
}
}
return minutes;
}
Try this
String str = "8:20";
int ans = (Integer.parseInt(str.split(":")[0])* 60)+Integer.parseInt(str.split(":")[1]);
System.out.println("Answer = "+ans);