Historical US dollar to euro conversion

一笑奈何 提交于 2019-12-12 06:30:05

问题


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:


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;
}


来源:https://stackoverflow.com/questions/41549315/historical-us-dollar-to-euro-conversion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!