将日期字符串解析为某个 Java 对象

发布于 2024-12-27 01:27:49 字数 469 浏览 0 评论 0原文

我正在从事一个读取文件和处理数据的项目。在那里,我必须处理日期,例如:

  1. 2012-01-10 23:13:26
  2. 2012 年 1 月 13 日

我找到了 Joda 包,有点有趣,但不知道它是否是最简单的。

我能够将第一个示例解析为 DateTime 对象(Joda)正则表达式和字符串操作。 (例如:通过用“-”替换空格并将其传递给构造函数。

new DateTime("2012-01-10 23:13:26".replace(' ', '-'))

我想它有效,但问题在于第二种格式。我如何使用这样的输入来提取对象,最好是 Joda 对象。我当然可以编写一个函数来将格式更改为 Joda 支持的格式,但想知道是否有其他方法(甚至是一些本机 Java 库)可以做到这一点,

如果有比 Joda 更好的东西,请告诉我。也

谢谢你。

I am working in a project that reads files and processes data. There I got to work with dates for example:

  1. 2012-01-10 23:13:26
  2. January 13, 2012

I found the package Joda, kinda interesting package but don't know if it is the easiest around.

I was able to parse the first example to a DateTime object (Joda) reg-ex and String manipulation. (Ex: by replacing the space by '-' and passing it to constructor.

new DateTime("2012-01-10 23:13:26".replace(' ', '-'))

I guess it worked, but the problem is with the second format. How can I use such an input to extract a an object, preferably a Joda object. I sure can write a function to change the format to what Joda supports, but was wondering if there would be some other way (even some native Java library) to do it.

If there are any thing better than Joda out there, please let me know it as well.

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

傲世九天 2025-01-03 01:27:50

使用 Joda-Time,请查看 日期时间格式;它允许解析您提到的两种日期字符串(以及几乎任何其他任意格式)。如果您的需求更复杂,请尝试 DateTimeFormatterBuilder< /a>.

要解析#1:

DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = f.parseDateTime("2012-01-10 23:13:26");

编辑:实际上 LocalDateTime对于没有时区的日期时间来说是更合适的类型:

LocalDateTime dateTime = f.parseLocalDateTime("2012-01-10 23:13:26");

对于#2:

DateTimeFormatter f = DateTimeFormat.forPattern("MMMM dd, yyyy");
LocalDate localDate = f.parseLocalDate("January 13, 2012");

是的,就 Java 日期和时间而言,Joda-Time 绝对是正确的选择。涉及时间处理。 :)

大多数人都会同意,Joda 是一个非常用户友好的库。例如,我以前从未用Joda做过这种解析,但我只花了几分钟就从API中弄清楚并编写了它。

更新(2015)

如果您使用的是Java 8,在大多数情况下您应该简单地使用java.time 而不是 Joda-Time。它几乎包含了 Joda 的所有好东西——或者类似的东西。对于那些已经熟悉 Joda API 的人,Stephen Colebourne 的 Joda -Time到java.time迁移指南派上用场了。

以下是上述示例的 java.time 版本。

解析#1:

DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.from(f.parse("2012-01-10 23:13:26"));

您无法将其解析为 ZonedDateTime 或 OffsetDateTime (它们是 Joda 的 DateTime 的对应项,在我的原始答案中使用),但这有点有意义,因为解析的字符串中没有时区信息。

解析 #2:

DateTimeFormatter f = DateTimeFormatter.ofPattern("MMMM dd, yyyy");
LocalDate localDate = LocalDate.from(f.parse("January 13, 2012"));

这里 LocalDate 是最适合解析的类型(就像 Joda-Time 一样)。

Using Joda-Time, take a look at DateTimeFormat; it allows parsing both kind of date strings that you mention (and almost any other arbitrary formats). If your needs are even more complex, try DateTimeFormatterBuilder.

To parse #1:

DateTimeFormatter f = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = f.parseDateTime("2012-01-10 23:13:26");

Edit: actually LocalDateTime is a more appropriate type for a datetime without a time zone:

LocalDateTime dateTime = f.parseLocalDateTime("2012-01-10 23:13:26");

And for #2:

DateTimeFormatter f = DateTimeFormat.forPattern("MMMM dd, yyyy");
LocalDate localDate = f.parseLocalDate("January 13, 2012");

And yes, Joda-Time is definitely the way to go, as far as Java date & time handling is concerned. :)

As mostly everyone will agree, Joda is an exceptionally user-friendly library. For example, I had never done this kind of parsing with Joda before, but it took me just a few minutes to figure it out from the API and write it.

Update (2015)

If you're on Java 8, in most cases you should simply use java.time instead of Joda-Time. It contains pretty much all the good stuff—or their equivalents—from Joda. For those already familiar with Joda APIs, Stephen Colebourne's Joda-Time to java.time migration guide comes in handy.

Here are java.time versions of above examples.

To parse #1:

DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.from(f.parse("2012-01-10 23:13:26"));

You cannot parse this into ZonedDateTime or OffsetDateTime (which are counterparts of Joda's DateTime, used in my original answer), but that kinda makes sense because there's no time zone information in the parsed string.

To parse #2:

DateTimeFormatter f = DateTimeFormatter.ofPattern("MMMM dd, yyyy");
LocalDate localDate = LocalDate.from(f.parse("January 13, 2012"));

Here LocalDate is the most appropriate type to parse into (just like with Joda-Time).

阳光①夏 2025-01-03 01:27:50

SimpleDateFormat 会将日期解析为 Java Date 对象:

http: //docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); // first example
SimpleDateFormat format2 = new SimpleDateFormat("MMMMM dd,yyyy"); // second example

Date d1 = format1.parse( dateStr1 );
Date d2 = format2.parse( dateStr2 );

SimpleDateFormat will parse dates into Java Date objects:

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); // first example
SimpleDateFormat format2 = new SimpleDateFormat("MMMMM dd,yyyy"); // second example

Date d1 = format1.parse( dateStr1 );
Date d2 = format2.parse( dateStr2 );
哆啦不做梦 2025-01-03 01:27:50

我想 Joda 有一个格式化程序可以为你做这件事。我通过快速谷歌搜索找到了这个: http://johannburkard.de /blog/programming/java/date-time-parsing-formatting-joda-time.html

DateTimeFormatter parser1 =
    DateTimeFormat.forPattern("dd/MMM/yyyy:HH:mm:ss Z");

DateTimeFormatter parser2 =
    DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");

DateTime time = parser1.parseDateTime("<data>");

用于评估模式的语法可以在 X-Zero 的链接

I would imagine Joda has something of a Formatter to do this for you. I found this with a quick google search: http://johannburkard.de/blog/programming/java/date-time-parsing-formatting-joda-time.html

DateTimeFormatter parser1 =
    DateTimeFormat.forPattern("dd/MMM/yyyy:HH:mm:ss Z");

DateTimeFormatter parser2 =
    DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");

DateTime time = parser1.parseDateTime("<data>");

The syntax that is used to evaluate the patterns can be found in X-Zero's link.

何以心动 2025-01-03 01:27:50

最简单的方法是根据您期望的格式正确设置 SimpleDateFormat 并使用其解析方法为您提供一个 Date 对象

Easiest would be setting up SimpleDateFormat properly as per the format you would expect and use its parse method to give you a Date object

今天小雨转甜 2025-01-03 01:27:50

tl;dr

LocalDateTime ldt = LocalDateTime.parse( "2012-01-10 23:13:26".replace( " " , "T" ) );

…and…

LocalDate localDate = LocalDate.parse ( "January 13, 2012" , DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG ).withLocale ( Locale.US ) );

详细信息

Jonik 的回答基本上是正确的,但遗漏了一些重要的问题。

java.time

如果有比 Joda 更好的东西,请也告诉我。

是的,有更好的东西,java.lang.时间框架。 Joda-Time 团队建议迁移到 java.time 作为其后继者。

java.time 框架是内置于 Java 8 及更高版本中。这些类取代了旧的麻烦的日期时间类,例如 java.util.Date、.Calendar 和 & 。 java.text.SimpleDateFormat

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。

许多 java.time 功能都向后移植到 Java 6 和 Java 6。 ThreeTen-Backport 中的 7 并在 ThreeTenABP

日期-时间

您的第一个输入是日期加时间。它缺少任何 offset-from-UTC时区 信息,因此我们将其解析为 LocalDateTime 对象。 “本地...”表示任何地点,没有特定地点。因此,这不是时间线上的实际时刻,而只是一个关于时刻的粗略想法。

要解析输入字符串 2012-01-10 23:13:26,我们可以用 T 替换中间的空格,以符合 ISO 8601 日期时间值的标准格式。

在解析和生成日期时间值的文本表示形式时,java.time 类默认使用 ISO 8601 格式。所以不需要定义解析模式。

String input = "2012-01-10 23:13:26".replace( " " , "T" );
LocalDateTime ldt = LocalDateTime.parse( input );

如果您从该值的上下文中知道预期的时区,则应用它来定义时间线上的实际时刻。

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ldt.atZone( zoneId );

转储到控制台。

System.out.println ( "input: " + input + " | zdt: " + zdt );

输入:2012-01-10T23:13:26 | zdt: 2012-01-10T23:13:26-05:00[美国/蒙特利尔]

仅日期

您输入的第二个值是仅日期值,没有时间和时区。为此,我们需要 LocalDate 类。

我认为该输入的格式符合美国的语言(英语)和文化规范。因此无需显式指定格式化模式。我们可以简单地通过指定 区域设置。我们指定 FormatStyle.LONG 适合此格式的长度。

String input = "January 13, 2012";
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG ).withLocale ( Locale.US );
LocalDate localDate = LocalDate.parse ( input , formatter );

转储到控制台。

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

输入:2012 年 1 月 13 日 |本地日期:2012-01-13

tl;dr

LocalDateTime ldt = LocalDateTime.parse( "2012-01-10 23:13:26".replace( " " , "T" ) );

…and…

LocalDate localDate = LocalDate.parse ( "January 13, 2012" , DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG ).withLocale ( Locale.US ) );

Details

The Answer by Jonik is basically correct but misses some important issues.

java.time

If there are any thing better than Joda out there, please let me know it as well.

Yes, there is something better, the java.time framework. The Joda-Time team advises migration to java.time as its successor.

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

Date-time

Your first input is a date plus a time-of-day. It lacks any offset-from-UTC or time zone info, so we parse it as a LocalDateTime object. The “Local…” means any locality, no specific locality. So it is not an actual moment on the timeline but rather just a rough idea about a moment.

To parse the input string 2012-01-10 23:13:26 we can replace the SPACE in the middle with a T to conform with the canonical style for the ISO 8601 standard format of date-time values.

The java.time classes use ISO 8601 formats by default when parsing and generating textual representations of date-time values. So no need to define a parsing pattern.

String input = "2012-01-10 23:13:26".replace( " " , "T" );
LocalDateTime ldt = LocalDateTime.parse( input );

If you know the the intended time zone from the context of this value, apply it to define an actual moment on the timeline.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ldt.atZone( zoneId );

Dump to console.

System.out.println ( "input: " + input + " | zdt: " + zdt );

input: 2012-01-10T23:13:26 | zdt: 2012-01-10T23:13:26-05:00[America/Montreal]

Date-only

The second of you inputs is a date-only value without time-of-day and without time zone. For that we need the LocalDate class.

I recognize the format of that input as complying with the language (English) and cultural norms of the United States. So no need to specify explicitly a formatting pattern. We can simply ask for a formatter that knows that US format by specifying a Locale. We specify FormatStyle.LONG as appropriate for the length of this format.

String input = "January 13, 2012";
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG ).withLocale ( Locale.US );
LocalDate localDate = LocalDate.parse ( input , formatter );

Dump to console.

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

input: January 13, 2012 | localDate: 2012-01-13

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文