如何在 java 中将字符串转换为日期对象

How to convert string to date object in java

我有一个这种格式的字符串 String oldstring = "Mar 19 2018 - 14:39";

如何将此字符串转换为 java 对象,以便我从日期对象中获取时间和分钟数。

我试过这样,

import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;

public class DateEg {
    public static final void main(String[] args) {
        SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm");
    String oldstring = "Mar 19 2018 - 14:39";
        String time = localDateFormat.format(oldstring);
        System.out.println(time);
    }
}

但是出现错误,说 Cannot format given Object as a Date

Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
    at java.base/java.text.DateFormat.format(DateFormat.java:332)
    at java.base/java.text.Format.format(Format.java:158)
    at DateEg.main(DateEg.java:9)

是否可以在 java 中解析此字符串格式?

尝试使用它,这应该有效:

DateTimeFormatter formatter = DateTimeFormat.forPattern("MMM dd yyyy - HH:mm");
LocalDateTime dt = formatter.parse(oldstring);`

DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm");
String time = timeFormat.format(dt).toString();`

使用您的代码使用正确的格式化程序来解析下面提到的字符串

    SimpleDateFormat localDateFormat = new SimpleDateFormat("MMM dd yyyy - HH:mm");
    String oldstring = "Mar 19 2018 - 14:39";
    Date date=localDateFormat.parse(oldstring);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    int hours = calendar.get(Calendar.HOUR_OF_DAY);
    int minutes = calendar.get(Calendar.MINUTE);
    int seconds = calendar.get(Calendar.SECOND);

如果您可以使用外部库,Apache Common DateUtils 提供了许多实用程序 类 可用于处理日期。 为了将您的字符串解析为一个对象,您可以使用例如:

public static Date parseDate(String str, Locale locale, String... parsePatterns) throws ParseException

Parses a string representing a date by trying a variety of different parsers, using the default date format symbols for the given locale.

The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.

The parser will be lenient toward the parsed date.

Parameters:str - the date to parse, not nulllocale - the locale whose date format symbols should be used. If null, the system locale is used (as per parseDate(String, String...)).parsePatterns - the date format patterns to use, see SimpleDateFormat, not nullReturns:the parsed dateThrows:IllegalArgumentException - if the date string or pattern array is nullParseException - if none of the date patterns were suitable (or there were none)Since:3.2

tl;博士

LocalDateTime.parse(                   // Parse as a `LocalDateTime` because the input lacks indication of zone/offset.
    "Mar 19 2018 - 14:39" , 
    DateTimeFormatter.ofPattern( "MMM dd uuuu - HH:mm" , Locale.US )
)                                      // Returns a `LocalDateTime` object.
.toLocalTime()                         // Extract a time-of-day value.
.toString()                            // Generate a String in standard ISO 8601 format.

14:39

java.time

现代方法使用 java.time 类.

定义格式模式以匹配您的输入。指定 Locale 以确定用于解析此本地化输入字符串的人类语言和文化规范。

String input = "Mar 19 2018 - 14:39" ;
Locale locale = Locale.US ;  // Specify `Locale` to determine human language and cultural norms used in parsing this localized input string.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM dd uuuu - HH:mm" , locale ) ;

解析为 LocalDateTime,因为输入缺少任何时区指示符或 offset-from-UTC。

LocalDateTime ldt = LocalDateTime.parse( input , f  );

提取 time-of-day 值,不带日期和时区,因为这是问题的目标。

LocalTime lt = ldt.toLocalTime();

ldt.toString(): 2018-03-19T14:39

lt.toString(): 14:39

ISO 8601

您输入的格式很糟糕。将 date-time 值序列化为文本时,始终使用标准 ISO 8601 格式。

java.time 类 在 parsing/generating 字符串时默认使用标准 ISO 8601 格式。你可以在这个答案中看到上面的例子。


关于java.time

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

Joda-Time project, now in maintenance mode, advises migration to the java.time 类.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

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

java.time类在哪里获取?

  • Java SE 8, Java SE 9,及以后
    • Built-in。
    • 标准 Java API 的一部分,带有捆绑实施。
    • Java 9 添加了一些小功能和修复。
  • Java SE 6 and Java SE 7
    • java.time 的大部分功能是 back-ported 到 Java ThreeTen-Backport 中的 6 和 7。
  • Android
    • Android java.time 类.
    • 捆绑实施的更高版本
    • 对于较早的 Android (<26),ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.