更改 Java 字符串中的日期格式 [英] Change date format in a Java string

查看:31
本文介绍了更改 Java 字符串中的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表示日期的 String.

I've a String representing a date.

String date_s = "2011-01-18 00:00:00.0";

我想将其转换为 Date 并以 YYYY-MM-DD 格式输出.

I'd like to convert it to a Date and output it in YYYY-MM-DD format.

2011-01-18

我怎样才能做到这一点?

How can I achieve this?

好的,根据我在下面检索到的答案,这是我尝试过的:

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.

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变成Date.

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()Date 格式化为特定模式的String.

Use SimpleDateFormat#format() to format a Date into a String in a certain pattern.

String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18

另见:

  • Java 字符串到日期的转换
  • 更新:根据您失败的尝试:模式区分大小写.阅读 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.

    这篇关于更改 Java 字符串中的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆