从数据库postgressql我得到日期的某个时间日期在不同的不同形式,如“2015-11-26 09:30:10”,“2015-11-26 09:30:10.080”,“2015-11- 26 09:30:10.000“现在我想将所有格式转换为仅格式22/01/2018如何在java中进行。
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!13/01 / 2014但是当我尝试
时 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.IllegalArgumentExceptionhow来解决这个问题
答案 0 :(得分:0)
试试这个
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);
}