我有一个非常奇怪的问题,就是一小段代码在一台机器上工作,而不是在另一台机器上工作。此代码:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
Map<LocalDate, Double> temperatur = new TreeMap<>();
for (LocalDate currentDate = LocalDate.parse("2014-jan-01", formatter); currentDate.getYear() < 2015; currentDate = currentDate.plusDays(1))
{
String date = currentDate.toString();
int stringIndex = (data.indexOf(date));
String tempString = data.substring((stringIndex + 31), (stringIndex + 35));
if(tempString.contains(";"))
tempString = tempString.substring(0, 3);
double temp = Double.parseDouble(tempString);
temperatur.put(currentDate, temp);
}给我一个例外:
Exception in thread "main" java.time.format.DateTimeParseException: Text '2014-jan-01' could not be parsed at index 5
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalDate.parse(Unknown Source)
at main.SMHITest.getValues(SMHITest.java:50)
at main.DataCollectionBuilder.addToResult(DataCollectionBuilder.java:46)
at main.DataCollectionBuilder.<init>(DataCollectionBuilder.java:25)
at main.ClientProgram.main(ClientProgram.java:14)正如您在for循环中可能猜到的那样,SMHITest.Java:50行是正确的。奇怪的是,这段代码在一台电脑上运行得很好,但却拒绝在家里为我工作。这两台机器都运行Eclipse,但是有一台机器(它工作的机器)运行java 1.8.0_112,另一台运行java1.8.0_121-B13。但我无法想象这就是问题所在?
发布于 2017-02-06 22:32:28
该错误是抛出的,因为它指定的日期"2014-jan-01“与格式yyyy-MMM-dd不匹配。必须是2014-1月-01
不知道你想在下面做些什么,
String tempString = data.substring((stringIndex + 31), (stringIndex + 35));
if(tempString.contains(";"))由于日期2014-01-0不包含';‘或它有35个字符的长度。
发布于 2017-02-14 16:26:47
使用新的java.time-API以不区分大小写的方式解析类似于"2014-jan-01“的字符串的唯一(也是很尴尬的)方法如下:
String input = "2014-jan-01";
DateTimeFormatter dtf =
new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("uuuu-MMM-dd")
.toFormatter().withLocale(Locale.ENGLISH);
LocalDate date = dtf.parse(input, LocalDate::from);
System.out.println(date); // 2014-01-01https://stackoverflow.com/questions/42078310
复制相似问题