在 Java 中以不同格式解析字符串到日期tl;博士详LocalDateDateTimeFormatter关于 java.time

2022-08-31 10:53:35

我想以不同的格式转换为。StringDate

例如

我从用户那里得到,

String fromDate = "19/05/2009"; // i.e. (dd/MM/yyyy) format

我想将其转换为格式的 Date 对象fromDate"yyyy-MM-dd"

我该怎么做?


答案 1

看看SimpleDateFormat。代码是这样的:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

try {

    String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
    e.printStackTrace();
}

答案 2

tl;博士

LocalDate.parse( 
    "19/05/2009" , 
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) 
)

其他带有 、 和 的答案现已过时。java.util.Datejava.sql.DateSimpleDateFormat

LocalDate

执行日期时间的现代方法是使用 java.time 类,特别是 .LocalDate 类表示一个仅日期值,不带时间,也不带时区。LocalDate

DateTimeFormatter

若要分析或生成表示日期时间值的 String,请使用 DateTimeFormatter 类。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "19/05/2009" , f );

不要将日期时间对象与表示其值的 String 混为一谈。日期时间对象没有格式,而 String 有格式。日期时间对象(如 )可以生成 String 来表示其内部值,但日期时间对象和 String 是单独的不同对象。LocalDate

您可以指定任何自定义格式来生成字符串。或者让java.time完成自动本地化的工作。

DateTimeFormatter f = 
    DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
                     .withLocale( Locale.CANADA_FRENCH ) ;
String output = ld.format( f );

转储到控制台。

System.out.println( "ld: " + ld + " | output: " + output );

ld: 2009-05-19 |产量:2009年19月19日

在 IdeOne.com 中查看实际操作


关于 java.time

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

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

要了解更多信息,请参阅 Oracle 教程。搜索 Stack Overflow 以获取许多示例和解释。规格是JSR 310

您可以直接与数据库交换 java.time 对象。使用符合 JDBC 4.2 或更高版本的 JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过其他类扩展了 java.time。这个项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuarter