Historical US dollar to euro conversion

224 views Asked by At

In a program, I use the following procedure to convert EUR in DOLLAR or vice-versa. In general, this procedure works fine with whatever currency.

public double getRate(String from, String to)
{
    BufferedReader reader = null;
    try
    {
        URL url = new URL("http://quote.yahoo.com/d/quotes.csv?f=l1&s=" + from + to + "=X");
        reader = new BufferedReader(new    InputStreamReader(url.openStream()));

        String line = reader.readLine();

        if (line.length() > 0)
        {
            return Double.parseDouble(line);
        }
    }
    catch (IOException | NumberFormatException e)
    {
        System.out.println(e.getMessage());
    }
    finally
    {
        if (reader != null)
        {
            try
            {
                reader.close();
            }
            catch(IOException e)
            {
            }
        }
    }

    return 0;
}

My problem is that I want to create a similar method for historical data. Basically, I need a method with the following signature:

public double getRate(String from, String to, Date date) {
   ...
}

that I can call in this way:

getRate("USD", "EUR", new SimpleDateFormat( "yyyyMMdd" ).parse( "20160104" ))

to get the value in EUR of 1$ in 2016/01/04 or whatever date in the past. I read lot of thread on StackOverflow and other similar website ma no solution found. I need a solution using a free service.

1

There are 1 answers

0
Salvatore D'angelo On

Thanks to Berger's answer I could implement my method. Here how it looks like. I hope it could be useful for someone else in this forum.

public double getRate(String from, String to, Date date) {
    BufferedReader reader = null;
    try {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = df.format(date);
        URL url = new URL("http://currencies.apps.grandtrunk.net/getrate/" + dateString +"/" + from + "/" + to);
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String line = reader.readLine();
        if (line.length() > 0) {
            return Double.parseDouble(line);
        }
    } catch (IOException | NumberFormatException e) {
        System.out.println(e.getMessage());
    } finally {
        if (reader != null) try { reader.close(); } catch(IOException e) {}
    }

    return 0;
}