LocalDateTime类 在 java.time包下。SimpleDateFormat 在java.text 包下
jdk1.8后才有的-> https://blog.fondme.cn/apidoc/jdk-1.8-google/
1.将本地时间System.currentTimeMillis()按照指定格式"yyyy-MM-dd HH:mm:ss"转化为字符串
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = dateformat.format(System.currentTimeMillis());
注:若精确到毫秒 则格式ss后加 .SSS(点SSS)即可,即:yyyy-MM-dd HH:mm:ss.SSS
另: "" + System.currentTimeMillis(); // 直接将long类型转换为字符串类型(不进行时间的转换),同理你懂的~
2.时间字符串("yyyy-MM-dd HH:mm:ss.SSS") 转换成毫秒(milliseconds)为:
long startTimeMillis = 0;
long endTimeMillis = 0;
try {
startTimeMillis = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(startTime).getTime();
endTimeMillis = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(endTime).getTime();
} catch (ParseException e) {
e.printStackTrace();
}
要注意:1. parse方法未捕获异常会出现 Unhandled exception: java.text.ParseException 错误,需要捕获异常
2. 时间戳为long 类型,而不是字符串类型
3. 将timeString (传进来的字符串类型的时间)转化为LocalDateTime对象(由字符串到对象的转化)
LocalDateTime time = LocalDateTime.parse(timeString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
至于为什么要转化为对象呢?我目前接触到的是可用于一些字符串不好处理的操作,用对象 可调用其封装好的方法
如:if (t.isAfter(startTime) && t.isBefore(endTime)){......}
t.isAfter(startTime) 意思是:检查时间t 是否在特定的时间start Time 之后
t.isBefore(endTime) 意思是:检查时间t 是否在特定的时间endTime 之前
当 t ,startTime,endTime 都是时间类型的对象的时候,可用LocalDateTime类中的一些时间处理的方法
举一个例子
// start,end 都为字符串类型的时间,格式为 yyyy-MM-dd HH:mm:sspublic static List<String> readLocatedLine(String start, String end, String id) {
LocalDateTime st = LocalDateTime.parse(start, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDateTime et = LocalDateTime.parse(end, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
List<String> list = new ArrayList<>();
BufferedReader br = null;
try { //如果没有缓冲,则每次调用read()或readLine()都会导致从文件中读取字节,并将其转换为字符后返回,而这是极其低效的。
br = new BufferedReader(new InputStreamReader(new FileInputStream("D:/**/**.txt"),"UTF-8"));
String line = null;
while ((line = br.readLine()) != null){
if (line.indexOf("标识性字符串") >= 0) {
String time = line.substring(0, 19);
LocalDateTime t = LocalDateTime.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
if (t.isAfter(st) && t.isBefore(et)) {
String str = line.substring(line.indexOf("标识性字符串") + 9);
if (str.contains(deviceId)) {
list.add(str);
}
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (br != null) { // br不为空指针
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}
另:readLine()函数读取一行时,如果某一行没有数据则为 " ",即:空字符串,只有到末尾才为null
-
new FileInputStream("D:/**/**.txt");
FileInputStream
从文件系统中的某个文件中获得输入字节。
用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader
。
-
new InputStreamReader(new FileInputStream("D:/**/**.txt"),"UTF-8");
InputStreamReader 是字节流通向字符流的桥梁:它使用指定的
读取字节并将其解码为字符。它使用的字符集可以由名称指定或显式给定,或者可以接受平台默认的字符集。charset
每次调用 InputStreamReader 中的一个 read() 方法都会导致从底层输入流读取一个或多个字节。要启用从字节到字符的有效转换,可以提前从底层流读取更多的字节,使其超过满足当前读取操作所需的字节。
为了提高效率,可考虑在 BufferedReader 内包装 InputStreamReader