java 如何在java中将字符串转换为日期对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49610244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert string to date object in java
提问by Arun
I have a string in this format
String oldstring = "Mar 19 2018 - 14:39";
我有一个这种格式的字符串
String oldstring = "Mar 19 2018 - 14:39";
How to convert this string to java object so that I get time and mins from date object.
如何将此字符串转换为 java 对象,以便从日期对象中获取时间和分钟数。
I have tried like this,
我试过这样,
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);
}
}
But getting error, saying Cannot format given Object as a Date
但是得到错误,说 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)
Is it possible to parse this string format in java?
是否可以在java中解析这种字符串格式?
回答by Akshay Batra
Try using this, this should work:
尝试使用这个,这应该有效:
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();`
回答by Dhiraj
User proper formatter with your code to parse string mentioned below
使用您的代码使用正确的格式化程序来解析下面提到的字符串
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);
回答by Basil Bourque
tl;dr
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
14:39
java.time
时间
The modern approach uses the java.timeclasses.
现代方法使用java.time类。
Define a formatting pattern to match your input. Specify Locale
to determine human language and cultural norms used in parsing this localized input string.
定义格式模式以匹配您的输入。指定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 ) ;
Parse as a LocalDateTime
because the input lacks any indicator of time zone or offset-from-UTC.
解析为 aLocalDateTime
因为输入缺少任何时区或UTC偏移量的指示符。
LocalDateTime ldt = LocalDateTime.parse( input , f );
Extract the time-of-day value, without a date and without a time zone, as that is the goal of the Question.
提取时间值,没有日期和时区,因为这是问题的目标。
LocalTime lt = ldt.toLocalTime();
ldt.toString(): 2018-03-19T14:39
lt.toString(): 14:39
ldt.toString(): 2018-03-19T14:39
lt.toString(): 14:39
ISO 8601
ISO 8601
The format of your input is terrible. When serializing date-time values as text, always use standard ISO 8601formats.
您输入的格式很糟糕。将日期时间值序列化为文本时,请始终使用标准ISO 8601格式。
The java.timeclasses use the standard ISO 8601 formats by default when parsing/generating strings. You can see examples above in this Answer.
所述java.time类解析/生成字符串时默认使用标准ISO 8601格式。你可以在这个答案中看到上面的例子。
About java.time
关于java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*
classes.
您可以直接与数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 更高版本的 Android 捆绑实现 java.time 类。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject 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.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。
回答by AR1
If you can use an external library, the Apache Common DateUtilsprovides many utility classes that you can use to work on dates. In order to parse your string to an object you can use for instance:
如果您可以使用外部库,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
通过尝试各种不同的解析器,使用给定语言环境的默认日期格式符号来解析表示日期的字符串。
解析将依次尝试每个解析模式。只有解析了整个输入字符串,解析才被认为是成功的。如果没有匹配的解析模式,则抛出 ParseException。
解析器将对解析日期宽容。
参数:str?- 要解析的日期,而不是 nulllocale?- 应使用其日期格式符号的区域设置。如果?null,则使用系统区域设置(根据?parseDate(String, String...))。parsePatterns?- 要使用的日期格式模式,请参阅 SimpleDateFormat,而不是 nullReturns:the parsed dateThrows:IllegalArgumentException?- 如果日期字符串或模式数组是 nullParseException?- 如果没有合适的日期模式(或没有)自:3.2