使用java8将字符串转换为日期 [英] Converting string to date using java8

查看:3541
本文介绍了使用java8将字符串转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java 8将字符串转换为日期,并将其转换为某种格式.下面是我的代码.即使在将格式模式提到为MM/dd/yyyy之后,我收到的输出也是yyyy/DD/MM格式.有人可以指出我做错了吗?

I am trying to convert a string to date using java 8 to a certain format. Below is my code. Even after mentioning the format pattern as MM/dd/yyyy the output I am receiving is yyyy/DD/MM format. Can somebody point out what I am doing wrong?

    String str = "01/01/2015";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    LocalDate dateTime = LocalDate.parse(str, formatter);
    System.out.println(dateTime);

推荐答案

那是因为您正在使用

That is because you are using the toString method which states that:

输出将采用ISO-8601格式uuuu-MM-dd.

The output will be in the ISO-8601 format uuuu-MM-dd.

您传递给LocalDate.parseDateTimeFormatter仅用于创建LocalDate,但并不附加"到创建的实例上.您将需要使用

The DateTimeFormatter that you passed to LocalDate.parse is used just to create a LocalDate, but it is not "attached" to the created instance. You will need to use LocalDate.format method like this:

String str = "01/01/2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate dateTime = LocalDate.parse(str, formatter);
System.out.println(dateTime.format(formatter)); // not using toString

这篇关于使用java8将字符串转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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