[英]How to get date in string and compare it using java
我有5個檔案。
1.ICAREP_ANI_SVCPROF_20120614_001.DAT
2.ICAREP_ANI_SVCPROF_20120617_001.DAT
3.ICAREP_ANI_SVCPROF_20120619_001.DAT
4.ICAREP_ANI_SVCPROF_20120615_001.DAT
5.ICAREP_ANI_SVCPROF_20120616_001.DAT
我想從該文件名中獲取日期(例如“ 20120614”),並比較每個日期以使用Java編程來查找最新的日期。
有人可以幫我嗎?
編輯! 下面是我的代碼:
String[] children = dir.list();
String test = "";
for (i=0; i<children.length; i++) {
test = children[i].compareTo(children[i+1]);
}
int numbDate = Integer.parseInt((String) str.subSequence(19, 27))
其中str是您的文件名。
這是您可以使用的簡單邏輯,
String filepath = "ICAREP_ANI_SVCPROF_20120614_001.DAT";
String [] tempPath = filepath.split("_");
System.out.println(""+tempPath[3]); //output = 20120614
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
try
{
Date date1 = ft.parse(tempPath[3]); //covert the string into date
}
catch(ParseException ex)
{
System.out.println(""+ex);
}
//compare the date logic
從下面的代碼中,您可以使用split(“ _”)獲得文件上的日期,因此文件名的長度無關緊要,
之后,您可以使用帶有“ yyMMdd”模式的SimpleDateFormat解析字符串。
然后使用ft.parse(string)生成Date對象。
如果您的文件名看起來總是一樣的,而無需提取日期,則可以對文件名使用字符串比較:
file1.getName().compareTo(file2.getName())
這樣您可以找到最新的。
這是一個班輪:
Date date = new SimpleDateFormat("yyyyMMdd").parse(filename.replaceAll(".*(\\d{8}).*", "$1"));
enter code here
String[] ar = { "ICAREP_ANI_SVCPROF_20120614_001.DAT", "ICAREP_ANI_SVCPROF_20120617_001.DAT",
"ICAREP_ANI_SVCPROF_20120619_001.DAT", "ICAREP_ANI_SVCPROF_20120615_001.DAT",
"ICAREP_ANI_SVCPROF_20120616_001.DAT" };
int latestIndex = 0;
int latest = 0;
String latestFile = ar[0];
for (int i = 0; i < ar.length; i++) {
String tempString = ar[i].substring(0, ar[i].lastIndexOf('_'));
latestFile = tempString.substring(tempString.lastIndexOf('_') + 1);
int current = Integer.parseInt(latestFile);
if (latest < current) {
latestIndex = i;
latest = current;
}
}
System.out.println("Latest file: " + ar[latestIndex]);
如果它們在特定的文件夾中,則可以首先獲取文件名,並進行相應的解析以獲取特定的字符串。 試試這個
`
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
if(fileEntry.getName().contains("20120614"){
//code to compare the latest date
}
}
}
}
試試看,我想這就是您想要的...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.