在Java字符串中更改日期格式
我有一个代表日期的 String
。
String date_s = "2011-01-18 00:00:00.0";
我想将其转换为日期
并将其输出到 YYYY-MM-DD
格式。
I'd like to convert it to a Date
and output it in YYYY-MM-DD
format.
2011- 01-18
2011-01-18
如何实现?
好的,根据下面我检索的答案,这里是我试过的东西:
Okay, based on the answers I retrieved below, here's something I've tried:
String date_s = " 2011-01-18 00:00:00.0";
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
Date date = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));
但是输出 02011-00-1
而不是所需的 2011-01-18
。我做错了什么?
But it outputs 02011-00-1
instead of the desired 2011-01-18
. What am I doing wrong?
使用 LocalDateTime#parse()
(或 ZonedDateTime#parse()
如果字符串恰好包含时区部分)来解析 String
以某种模式转换为 LocalDateTime
。
Use LocalDateTime#parse()
(or ZonedDateTime#parse()
if the string happens to contain a time zone part) to parse a String
in a certain pattern into a LocalDateTime
.
String oldstring = "2011-01-18 00:00:00.0";
LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));
使用 LocalDateTime#format()
(或将 ZonedDateTime#format()
)将 LocalDateTime
格式化为 String
以某种模式。
Use LocalDateTime#format()
(or ZonedDateTime#format()
) to format a LocalDateTime
into a String
in a certain pattern.
String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18
或,当你不在Java 8上,使用 SimpleDateFormat#parse()
将某个模式中的 String
解析成日期
。
Or, when you're not on Java 8 yet, use SimpleDateFormat#parse()
to parse a String
in a certain pattern into a Date
.
String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);
使用 SimpleDateFormat#format()
进行格式化日期
以 String
为特定模式。
String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18
另请参见:
- Java字符串到日期转换
- Java string to date conversion
See also:
更新:根据您的失败尝试: 区分大小写。阅读 java.text.SimpleDateFormat
javadoc 个别部件代表什么。所以代表例如 M
几个月,而 m
分钟。而且,有四位数字 yyyy
,而不是五个 yyyyy
。仔细看看我上面发贴的代码段。
Update: as per your failed attempt: the patterns are case sensitive. Read the java.text.SimpleDateFormat
javadoc what the individual parts stands for. So stands for example M
for months and m
for minutes. Also, years exist of four digits yyyy
, not five yyyyy
. Look closer at the code snippets I posted here above.