Need to display current day,previous day,last twodays data in my code using java

Hi Experts,

i want to display list values based on now(current day),last day(current date+previous day),last two days.
List<PerformanceDataValues> dataList = new ArrayList<>();
                for (Entry<String, String> entry : treemap.entrySet()) {
                    PerformanceDataValues data = new PerformanceDataValues();
                    data.setTime(entry.getKey());
                    String value = entry.getValue();
                    String computedValue = applyFormula(value, wsdlInput.getFormulae());
                    data.setValue(computedValue != null ? computedValue : value);
                    dataList.add(data);
                }

Open in new window


this list will have values as below,
every time this list will have last 3 days data.
i want to display 3 different outputs

a) days as 0
i have to display current date---> time and values information

b) days as 1
i have to display current day and previous day

c) days as 3

last 3days data

in method parameter i am passing the input value for days.
MeasurementInput input
input.getDays() will give value as 0 or 1 or  2 based on the value i have to show any of the data




dataList sample values:
=======================
 
      {
        "time": "2016-1-10 13:30:00",
        "value": 253.000
        },
        {
        "time": "2016-1-10 13:30:00",
        "value": 53.000
        },
        {
        "time": "2016-1-11 13:30:00",
        "value": 353.000
        },
        {
        "time": "2016-1-11 13:30:00",
        "value": 3.000
        },
        {
        "time": "2015-1-12 13:30:00",
        "value": 30.000
        },
        {
        "time": "2015-1-12 13:30:00",
        "value": 23.000
        }


THANKS
LVL 2
srikoteshAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

srikoteshAuthor Commented:
Please find the attachement to see complete method ....
history.txt
zzynxSr. Software engineerCommented:

1. From String to Date

First of all, you'll have to convert the "time" string in the data to real Date objects.
public Date convertStringToDate(String dateString)
{
    Date date = null;
    Date formatteddate = null;
    DateFormat df = new SimpleDateFormat("yyyy-M-dd HH:mm:ss");
    try{
        date = df.parse(dateString);
        formatteddate = df.format(date);
    }
    catch ( Exception ex ){
        System.out.println(ex);
    }
    return formatteddate;
}

Open in new window


2. Date aritmethics

You do Date aritmethics as follows:
Calendar cal = Calendar.getInstance(); // now
cal.add(Calendar.DATE, -1); // Minus one day
Date yesterday = cal.getTime();
cal.add(Calendar.DATE, -1); // Minus one day
Date dayBeforeYesterday = cal.getTime();

3. Comparing two Dates

And then you'll have to compare the Date from the "time" string with one or more of the above dates to check whether to show the corresponding values or not.For that you can use the Date's methods before() and after()

Eg.
if ( convertStringToDate(myDatasTimeString).before(yesterday) {
       // Show this data instance's values
}

Open in new window

If you have any questions about the above feel free to ask me

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
srikoteshAuthor Commented:
Hi ZZYNX,

I have made changes as per your suggerstion.
Please verify my code.
if possible trim the code i mean i have written 100 lines of code to achieve this.

package com.srini;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MapExamples4 {

	public static void main(String[] args) throws ParseException {
		Map<String, String> map = new TreeMap<>();
		map.put("2016-01-14 13:30:00", "253.000");
		map.put("2016-01-14 12:30:00", "53.000");
		map.put("2016-01-15 10:30:00", "353.000");
		map.put("2016-01-15 01:30:00", "563.000");
		map.put("2016-01-16 02:30:00", "693.000");
		map.put("2016-01-16 03:30:00", "283.000");
		map.put("2016-01-15 09:30:00", "273.000");
		Set<String> dateval = map.keySet();
		System.out.println(dateval);
		List<Date> list = new ArrayList<>();
		for (String strDate : dateval) {
			list.add(convertStringToDate(strDate));
		}

		//int days = 2;//To Get Last two days data.
		int days = 1; //To Get current date values
		Map<String, String> filteredMap = new LinkedHashMap<String, String>();
		if (days == 2) {
			filteredMap = getPreviousDateMap(map, list, filteredMap);
		} else if (days == 1) {
			filteredMap = getCurrentDateMap(map, list, filteredMap);
		}

	}

	private static Map<String, String> getCurrentDateMap(Map<String, String> map, List<Date> list,
			Map<String, String> filteredMap) throws ParseException {
		Date d2 = getPreviousDay(1);
		System.out.println("d2 value is" + d2);
		List<Date> afterDateList = new ArrayList<Date>();
		for (Date dateList : list) {
			if (d2.before(dateList)) {
				afterDateList.add(dateList);
			}
		}
		System.out.println("current date is " + afterDateList);
		getFilteredMap(map,filteredMap,afterDateList);
		return filteredMap;
	}

	private static Map<String, String> getPreviousDateMap(
			Map<String, String> map, List<Date> list,
			Map<String, String> filteredMap) throws ParseException {
		Date d1 = getPreviousDay(2);
		System.out.println("d1 value is" + d1);
		List<Date> currentDateList = new ArrayList<Date>();
		for (Date dateList : list) {
			if (d1.before(dateList)) {
				currentDateList.add(dateList);
			}
		}
		System.out.println("before date is " + currentDateList);
		getFilteredMap(map, filteredMap, currentDateList);
		return filteredMap;
	}

	private static void getFilteredMap(Map<String, String> map,
			Map<String, String> filteredMap, List<Date> currentDateList)
			throws ParseException {
		for (Date date : currentDateList) {
			filteredMap.put(convertDateToString(date),
					map.get(convertDateToString(date)));
		}
		System.out.println("FILTERED MAP IS" + filteredMap);
	}

	public static Date convertStringToDate(String strDate)
			throws ParseException {
		DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df2.parse(strDate);
	}

	public static String convertDateToString(Date strDate)
			throws ParseException {
		DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df2.format(strDate);
	}

	public static Date getPreviousDay(int days) {
		Calendar cal = Calendar.getInstance(); // now
		cal.add(Calendar.DATE, -days); // Minus one day
		return cal.getTime();
	}

}

Thanks,

Open in new window

JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

zzynxSr. Software engineerCommented:
if possible trim the code
I would first like you to make it work correctly. Once that is the case, then it is the right time to trim.

I don't know exactly what you're trying to do, but the lines

System.out.println("current date is " + afterDateList);

Open in new window

and
System.out.println("before date is " + currentDateList);

Open in new window

are definitely wrong since afterDateList and currentDateList are ... well Lists of Date's, not one Date.

To avoid calling the method convertDateToString() twice, you can better write
        for (Date date : currentDateList) {
            filteredMap.put(convertDateToString(date),
                map.get(convertDateToString(date)));
        }

Open in new window

as
        for (Date date : currentDateList) {
            String dateAsString = convertDateToString(date);
            filteredMap.put(dateAsString, map.get(dateAsString));
        }

Open in new window


Also, it looks strange to me that you call the result of getPreviousDay(1) "d2"
Date d2 = getPreviousDay(1);

Open in new window

while some lines further you call the result of getPreviousDay(2) "d1"
Date d1 = getPreviousDay(2);

Open in new window

Give your variables clear names; names that indicate what is in it.

Other observation:
Calendar cal = Calendar.getInstance(); // now

Open in new window

This is really now, including hours, minutes, seconds, milliseconds.
Are you sure this is what you want?
Or do you want to start your day limits at midnight?
If you want the latter, you should change the method getPreviousDay() as follows:

    public static Date getPreviousDay(int days) {
        Calendar cal = Calendar.getInstance(); // now
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0); // today @ midnight
        cal.add(Calendar.DATE, -days); // Minus one day
        return cal.getTime();
    }

Open in new window

srikoteshAuthor Commented:
System.out.println("current date is " + afterDateList);

the above line will print array of list
i can change it as afterDateList.toString();


Date d2 = getPreviousDay(1);
Date d1 = getPreviousDay(2);
i am not sure how to use after method so what i did is for both i have user before method

i may get input 1 or 2
if it is 1 i want to display current date
if it is 2  then i want to display current and previous dates.

int days = 1; //To Get current date values
getCurrentDateMap()
i am getting the o/p as below:
current date is [Mon Jan 18 02:30:00 IST 2016, Mon Jan 18 03:30:00 IST 2016]
FILTERED MAP IS{2016-01-18 02:30:00=693.000, 2016-01-18 03:30:00=283.000}

int days = 2;//To Get Last two days data.
getPreviousDateMap()
i am getting the o/p as below:
before date is [Sun Jan 17 01:30:00 IST 2016, Sun Jan 17 09:30:00 IST 2016, Sun Jan 17 10:30:00 IST 2016, Mon Jan 18 02:30:00 IST 2016, Mon Jan 18 03:30:00 IST 2016]
FILTERED MAP IS{2016-01-17 01:30:00=563.000, 2016-01-17 09:30:00=273.000, 2016-01-17 10:30:00=353.000, 2016-01-18 02:30:00=693.000, 2016-01-18 03:30:00=283.000}

in map i took static date values due to that result got confused.

do you want to start your day limits at midnight?
not required as of now.

Please find the attached code.
MapExample.txt
zzynxSr. Software engineerCommented:
the above line will print array of list
I know. But I find it very strange to read a sentence like this:
"current date is [Mon Jan 18 10:30:00 CET 2016, Tue Jan 19 02:30:00 CET 2016, Tue Jan 19 03:30:00 CET 2016]"
So the current date is three dates at the same time?

OK. Since your code works as you expect, I think we're done here.
Or do you still expect something from me?

if possible trim the code
I think your code is just fine as it is now.
zzynxSr. Software engineerCommented:
Thanx 4 axxepting
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.