java修改日期格式date_如何更改Java中的日期格式?

tl; dr

LocalDate.parse(

"23/01/2017" ,

DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK )

).format(

DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK )

)

2017/01/23

避免使用旧的日期时间类

克里斯托弗·帕克(Christopher Parker)的答案是正确的,但已经过时了。 麻烦的旧日期时间类,例如2709480612167156156736、YearQuarter和YearQuarter,现在已被遗留,由java.time类取代。

使用java.time

将输入的字符串解析为日期时间对象,然后以所需的格式生成一个新的String对象。

YearQuarter类表示不带日期和时区的仅日期值。

DateTimeFormatter fIn = DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK ); // As a habit, specify the desired/expected locale, though in this case the locale is irrelevant.

LocalDate ld = LocalDate.parse( "23/01/2017" , fIn );

为输出定义另一个格式化程序。

DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK );

String output = ld.format( fOut );

2017/01/23

顺便说一句,请考虑将标准ISO 8601格式用于表示日期时间值的字符串。

关于java.time

java.time框架内置于Java 8及更高版本中。 这些类取代了麻烦的旧的旧式日期时间类,例如YearQuarter、2709480612167156156和YearQuarter。

现在处于维护模式的Joda-Time项目建议迁移到java.time类。

要了解更多信息,请参见Oracle教程。 并在Stack Overflow中搜索许多示例和说明。 规格为JSR 310。

在哪里获取java.time类?

Java SE 8,Java SE 9和更高版本内置的

标准Java API的一部分,具有捆绑的实现。

Java 9添加了一些次要功能和修复。

Java SE 6和Java SE 7许多java.time功能都在ThreeTen-Backport中反向移植到Java 6和7。

安卓系统ThreeTenABP项目专门针对Android改编了ThreeTen-Backport(如上所述)。

请参阅如何使用ThreeTenABP…。

ThreeTen-Extra项目使用其他类扩展了java.time。 该项目为将来可能在java.time中添加内容提供了一个试验场。 您可能会在这里找到一些有用的类,例如YearQuarter、YearQuarter、YearQuarter等。

乔达时代

更新:Joda-Time项目现在处于维护模式,团队建议迁移到java.time类。 为了历史起见,在此保留本节。

为了好玩,这里是他的代码,适合使用Joda-Time库。

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

// import org.joda.time.*;

// import org.joda.time.format.*;

final String OLD_FORMAT = "dd/MM/yyyy";

final String NEW_FORMAT = "yyyy/MM/dd";

// August 12, 2010

String oldDateString = "12/08/2010";

String newDateString;

DateTimeFormatter formatterOld = DateTimeFormat.forPattern(OLD_FORMAT);

DateTimeFormatter formatterNew = DateTimeFormat.forPattern(NEW_FORMAT);

LocalDate localDate = formatterOld.parseLocalDate( oldDateString );

newDateString = formatterNew.print( localDate );

转储到控制台...

System.out.println( "localDate: " + localDate );

System.out.println( "newDateString: " + newDateString );

运行时...

localDate: 2010-08-12

newDateString: 2010/08/12

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值