将 Java 日期时间字符串更改为日期
Change a Java date-time string to date
好吧,我试图寻找很多问题,但找不到相关的东西。我有一个包含以下数据的字符串:
String sDate = "2018-01-17 00:00:00";
这个来自一个应用程序,我需要把它转换成下面的日期格式
17-01-2018
我经历了这个 link 但无法联系起来。
有人可以帮忙吗..?
您需要使用 SimpleDateFormat:
String sDate = "2018-01-17 00:00:00";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = df.parse(sDate);
SimpleDateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(df1.format(date));
通过 SimpleDateFormat class 了解详情
如果您使用的是 Java 8,则可以使用 java.time 库和 :
String sDate = "2018-01-17 00:00:00";
//Step one : convert the String to LocalDateTime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date = LocalDateTime.parse(sDate, formatter);
//Step two : format the result date to dd-MM-yyyy
String result = date.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
输出
17-01-2018
另一个过度工程解决方案(它只适用于您的情况)您可以从 LocalDateTime
的默认格式中受益:
String result = LocalDateTime.parse(sDate.replace(" ", "T"))
.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
public static void main(String args[]) {
String sDate = "2018-01-17 00:00:00";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = df.parse(sDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleDateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(df1.format(date));
}
it should solve your problem.
好吧,我试图寻找很多问题,但找不到相关的东西。我有一个包含以下数据的字符串:
String sDate = "2018-01-17 00:00:00";
这个来自一个应用程序,我需要把它转换成下面的日期格式
17-01-2018
我经历了这个 link 但无法联系起来。
有人可以帮忙吗..?
您需要使用 SimpleDateFormat:
String sDate = "2018-01-17 00:00:00";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = df.parse(sDate);
SimpleDateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(df1.format(date));
通过 SimpleDateFormat class 了解详情
如果您使用的是 Java 8,则可以使用 java.time 库和 :
String sDate = "2018-01-17 00:00:00";
//Step one : convert the String to LocalDateTime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date = LocalDateTime.parse(sDate, formatter);
//Step two : format the result date to dd-MM-yyyy
String result = date.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
输出
17-01-2018
另一个过度工程解决方案(它只适用于您的情况)您可以从 LocalDateTime
的默认格式中受益:
String result = LocalDateTime.parse(sDate.replace(" ", "T"))
.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
public static void main(String args[]) {
String sDate = "2018-01-17 00:00:00";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = df.parse(sDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleDateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(df1.format(date));
}
it should solve your problem.