我知道我可能做错了什么,但我正在尝试格式化当前存储在字符串内的
Date
,但它不会让我将其解析为String
,因为它无法识别它作为 Date
(因为它位于 String
变量中)并且不会让我格式化它,因为它无法在当前状态下格式化它。作为参考,我正在制作一个时钟应用程序。
如果我做了一些愚蠢的事情,我很抱歉,但我对此还很陌生,以前从未使用过
SimpleDateFormat
。我在下面放了一些代码片段:
ArrayList<String> punchHistoryTimes = new ArrayList<String>();
SimpleDateFormat sdf =new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public void updatePunchHistory(Sheet sheet){
for(int rowNum:rowNumbers){
punchHistoryTimes.add(sheet.getRow(rowNum).getCell(1).getStringCellValue());
punchHistory.add(new JLabel(sheet.getRow(rowNum).getCell(0).getRichStringCellValue().getString()+ " " + sheet.getRow(rowNum).getCell(1).getRichStringCellValue().getString()+ " " + sheet.getRow(rowNum).getCell(2).getRichStringCellValue().getString()));
}
}
//other code is above this but not relevant to the issue
currentEmployee.setEndTime(sdf.format(currentDate));
if(punchHistory.get(punchHistory.size()-1).getText().contains("Clocked In")){
calcTimeWorked(punchHistory.get(punchHistoryTimes.size()-1).getText(),currentEmployee.getEndTime());
}else{
//This line below is where the error is happening
//value of currentEmployee.getStartTime() at error: 1654653731536
//value of currentEmployee.getEndTime() at error: 07-06-2022 21:02:12
//Both currentEmployee.getStartTime() and currentEmployee.getEndTime() are stored as Strings
calcTimeWorked(currentEmployee.getStartTime(),currentEmployee.getEndTime());
}
currentEmployee.setHoursWorked(differenceInTime);
我尝试使用调试器,它显示错误是无法解析 1654653731536。我理解这个问题,但无法得到解决方案。我认为问题是因为当它将值存储在 Excel 文件中时,它将日期存储为字符串,但是当它稍后从 Excel 中提取日期时(应用程序将在这些事件之间关闭),它会查看它作为字符串,并且无法识别
Date
内部有 String
。有没有办法将 String
1654653731536 转换为 Date
?
您正在尝试隐藏纪元日期时间,下面的示例可能会帮助您
import java.util.Date;
public class EpochToDateFormat {
public static void main(String[] args) {
// Epoch time in milliseconds
long epochTime = 1654653731536L;
// Convert epoch time to Date
Date date = new Date(epochTime);
// Format Date to desired format
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String formattedDate = dateFormat.format(date);
// Output formatted date
System.out.println("Formatted Date: " + formattedDate);
}
}