一、关于日期类Date、Calendar、SimpleDateFormat的使用
1.Date类直接new进行时间设置时,其year字段是从1900年开始,month字段是从0开始,例如new Date(1998,5,5),最终得年份为 1900+1998,月份为6月,与预期的结果相悖;可使用system.currentTimeMills()获取当前时间毫秒值,使用构造方法Date(long time),来创建date对象;
public class testDate {
public static void main(String[] args){
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String format = dateFormat.format(date);
System.out.println(format);
}
}
2.Calendar类创建时可通过静态方法getInstance()进行创建,其用set()方法设置时间时,如calendar.set(1998,5,5),最终的结果为1998-6-5,其month字段也是从0开始的;因此在设置时间时,需将输入的月份减1;
3.使用SimpleDateFormat类,SimpleDateFormat类可直接new进行创建,其构造参数可传入构造格式,如 “yyyy-MM-dd HH:mm:ss”,可用simpleDateFormat.parse(“1998-5-5”)方法直接得到Date对象,其结果与预想的一样。同样,想要以特定的格式输出Date对象,也可使用该类的format()方法,其返回Date对象的字符串。
对你有用的话请点赞关注,记录不易,谢谢!
代码
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReadData {
public static void main(String[] args) throws IOException, ParseException {
String filepath ="D:\\Java\\Java自学笔记\\出租车数据.txt";
readTXT(filepath);
}
public static List<CarInfo> readTXT(String filepath) throws IOException, ParseException {
List<CarInfo> list =new ArrayList<>();
FileReader fileReader = new FileReader(filepath);
char[] chars = new char[50];
int length;
String text="";
while ((length=fileReader.read(chars))!=-1){
String s=new String(chars,0,length);
text+=s;
}
Pattern pattern = Pattern.compile("(\\w{2}),(\\d{1}),((\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})),(\\d+\\.\\d+),(\\d+\\.\\d+)");
Matcher matcher = pattern.matcher(text);
while (matcher.find()){
CarInfo carInfo = new CarInfo();
carInfo.setId(matcher.group(1));
carInfo.setState(Integer.parseInt(matcher.group(2)));
/*Date date = new Date(//此方法有问题,创建的时间并不是输入的时间,而是经过了处理
Integer.parseInt(matcher.group(4)),Integer.parseInt(matcher.group(5)),
Integer.parseInt(matcher.group(6)),Integer.parseInt(matcher.group(7)),
Integer.parseInt(matcher.group(8)),Integer.parseInt(matcher.group(9)));*/
/*Calendar instance = Calendar.getInstance();
instance.set(Integer.parseInt(matcher.group(4)),Integer.parseInt(matcher.group(5)),
Integer.parseInt(matcher.group(6)),Integer.parseInt(matcher.group(7)),
Integer.parseInt(matcher.group(8)),Integer.parseInt(matcher.group(9)));
Date date = instance.getTime();*/
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = simpleDateFormat.parse(matcher.group(3));
String format = simpleDateFormat.format(date);
System.out.println(format);
carInfo.setDate(date);
carInfo.setX(Double.parseDouble(matcher.group(10)));
carInfo.setY(Double.parseDouble(matcher.group(11)));
list.add(carInfo);
}
System.out.println(list);
return list;
}
}
本文介绍Java中Date、Calendar和SimpleDateFormat类的使用方法,包括如何正确设置和解析日期时间,以及常见陷阱避免。
2143

被折叠的 条评论
为什么被折叠?



