gpt4 book ai didi

java - 将字符串解析为 GregoriamCalendar 类型以在 ArrayList 中使用时遇到问题

转载 作者:行者123 更新时间:2023-11-30 03:10:40 26 4
gpt4 key购买 nike

所以我在这里遇到了一些麻烦 - 我正在尝试创建一个类来从雅虎下载历史股票市场数据。基本上,在第 64 行,我需要将 yyyy-MM-dd 形式的字符串解析为 GregorianCalendar 类型。我已经尝试了一段时间,并在此处和其他地方查看其他解决方案 - 虽然我可以将字符串解析为公历,但我无法将其以相同的形式 yyyy-MM-dd 添加到 ArrayList 日期。我使用 .split(,) 将 csv 的每一行拆分为单独的元素,所有其他类型都是 double 和整数,这很容易。

line 返回一个字符串,例如: 2015-11-12,116.260002,116.82,115.650002,115.720001,32262600,115.720001

提前致谢!

    public StockDownloader(String symbol, GregorianCalendar start, GregorianCalendar end) { 
dates = new ArrayList<GregorianCalendar>();
opens = new ArrayList<Double>();
highs = new ArrayList<Double>();
lows = new ArrayList<Double>();
closes = new ArrayList<Double>();
volumes = new ArrayList<Integer>();
adjCloses = new ArrayList<Double>();

//deconstructed URL
String url = "http://real-chart.finance.yahoo.com/table.csv?s="+symbol+
"&a="+start.get(Calendar.MONTH)+
"&b="+start.get(Calendar.DAY_OF_MONTH)+
"&c="+start.get(Calendar.YEAR)+
"&d="+end.get(Calendar.MONTH)+
"&e="+end.get(Calendar.DAY_OF_MONTH)+
"&f="+end.get(Calendar.YEAR)+
"&g=d&ignore=.csv";

try {
URL yhoofin = new URL(url); //creates URL from String url
URLConnection data = yhoofin.openConnection(); //invokes openConnection method on URL
Scanner input = new Scanner(data.getInputStream()); //Returns an input stream that reads from this open connection.
if(input.hasNext()) //skip line, it's just the header
input.nextLine(); //advances to next line

//start reading data
while(input.hasNextLine()) {
String line = input.nextLine();

String[] splitLine = line.split(",");

>>Problem here //dates.add( add the date );
opens.add(Double.parseDouble(splitLine[OPEN]));
highs.add(Double.parseDouble(splitLine[HIGH]));
lows.add(Double.parseDouble(splitLine[LOW]));
closes.add(Double.parseDouble(splitLine[CLOSE]));
volumes.add(Integer.parseInt(splitLine[VOLUME]));
adjCloses.add(Double.parseDouble(splitLine[ADJCLOSE]));


}
}
catch(Exception e) { //catch any error (exception) that happens
System.err.println(e);
}
}

最佳答案

您应该将日期存储在列表中,而不是 GregorianCalendar 而是日期:

List<Date> dates = new ArrayList<>()

然后您可以使用 SimpleDateFormat 解析日期:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
...
dates.add(format.parse(splitLine[0]));

SimpleDateFormat 可以帮助您将日期格式化为字符串,例如:

SimpleDateFormat newFormat = new SimpleDateFormat("dd-MM-yyyy HH"); //another format
String formattedDate = newFormat.format(date); //14-11-2015 11

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html http://docs.oracle.com/javase/7/docs/api/java/util/Date.html

关于java - 将字符串解析为 GregoriamCalendar 类型以在 ArrayList 中使用时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33699643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com