如何使用java将多种日期格式转换为一种格式
从数据库postgressql中,我得到了不同格式的日期,如“2015-11-26 09:30:10”、“2015-11-26 09:30:10.080”、“2015-11-26 09:30:10.000”现在我想转换所有格式,因为只有这种格式2018年1月22日在java中如何操作如何使用java将多种日期格式转换为一种格式,java,Java,从数据库postgressql中,我得到了不同格式的日期,如“2015-11-26 09:30:10”、“2015-11-26 09:30:10.080”、“2015-11-26 09:30:10.000”现在我想转换所有格式,因为只有这种格式2018年1月22日在java中如何操作 try { Date theDate1 = new Date("JAN 13,2014 09:15"); SimpleDateFormat format1 = new Sim
try {
Date theDate1 = new Date("JAN 13,2014 09:15");
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
} catch (Exception e {
System.out.println(e.toString());
}
我得到的输出是Hello,World!2014年1月13日但当我尝试
try {
Date theDate1 = new Date("2017-11-27 00:00:00");
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
} catch (Exception e) {
System.out.println(e.toString());
}
然后我得到了java.lang.illegalargumentException如何解决这个问题
String text = "JAN 13,2014 09:15";
String patternst = "\\d\\d\\d\\d-\\d\\d-\\d\\d*";
Pattern pattern = Pattern.compile(patternst);
Matcher matcher = pattern.matcher(text);
String data = "";
while (matcher.find()) {
data = matcher.group(0);
}
try {
int year = Integer.parseInt(data.split("-")[0]);
int month = Integer.parseInt(data.split("-")[1]);
int day = Integer.parseInt(data.split("-")[2]);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, day);
Date theDate1 = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
} catch (Exception e) {
Date theDate1 = new Date(text);
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String temp = format1.format(theDate1);
System.out.println("Hello, World! " + temp);
}
请阅读并花时间将您的问题编排为易读的格式。使用编辑器框下方的预览,以便检查文章是否可读。是否使用JDBC?而不是用于从数据库接收日期。在此之后,您可以使用@Edwardth格式化日期
java.sql.Timestamp
类现在是遗留类,被JDBC 4.2及更高版本的java.time.Instant
所取代<代码>Instant Instant=myResultSet.getObject(…,Instant.class)同样地,SimpleDateFormat
被DateTimeFormatter
取代。麻烦的日期时间类现在是遗留的,完全被现代的java.time
类取代。今天使用它们是不明智的。