java将字符串转换为日期对象_如何在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中解析这个字符串格式是可能的吗?

您的格式掩码已关闭。您指定的掩码只有小时和分钟,但时间戳远不止这些。

你的题目是"将字符串转换为日期"。您确定要使用format而不是parse吗?

我们将对象格式化为文本,将文本解析为对象。

我对格式和解析有误解。谢谢@ PSHEMO

@词典编号。我要分析字符串。

@然后阿伦打电话给parse。

FYY,麻烦的旧日期时间类,如EDCOX1,3,EDCOX1,4,EDCX1,5,都是遗留的,被Java.Times类替换为Java 8和更高版本。请参见Oracle教程。

DR

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.时间

现代方法使用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,因为输入缺少时区或与UTC的偏移量的任何指示器。

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

提取一天中的时间值,不带日期和时区,因为这是问题的目标。

LocalTime lt = ldt.toLocalTime();

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

lt.toString(): 14:39

国际标准化组织8601

你输入的格式很糟糕。将日期时间值序列化为文本时,请始终使用标准ISO 8601格式。

在解析/生成字符串时,java.time类默认使用标准的iso8601格式。你可以在这个答案中看到上面的例子。关于JavaTimes

JavaTimeFr框架是在Java 8和之后构建的。这些类取代了麻烦的旧遗留日期时间类,如java.util.Date、Calendar、&SimpleDateFormat。

现在处于维护模式的joda time项目建议迁移到java.time类。

要了解更多信息,请参阅Oracle教程。以及搜索堆栈溢出以获得许多示例和解释。规格为JSR 310。

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

在哪里获取java.time类?

Java SE 8、Java SE 9及以后

内置的。

标准JAVA API的一部分与捆绑实现。

Java 9添加了一些小的特性和修复。

Java SE 6和Java SE 7

大部分JavaTimeActudio都被移植到TealEnter后端的Java 6和7中。

安卓

java.time类的Android包实现的更高版本。

对于早期的Android(<26),threetenabp项目适应threeten backport(如上所述)。看看如何使用三连珠……

threeten额外项目使用额外的类扩展java.time。这个项目是将来可能添加到java.time的一个试验场。您可以在这里找到一些有用的类,如Interval、YearWeek、YearQuarter等等。

使用正确的格式化程序对下面提到的字符串进行分析

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);

如何只从日期对象获取小时和分钟?

@阿伦看我编辑的答案

FYY,麻烦的旧日期时间类,如EDCOX1,3,EDCOX1,4,EDCX1,5,都是遗留的,被Java.Times类替换为Java 8和更高版本。请参见Oracle教程。

尝试使用这个,应该可以:

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();`

您可能应该提到第一个版本使用了joda-time API:joda.org/joda-time/apidocs

@D.J.Brown或java.time.format。

我提交了一个编辑建议来引用,只是等待批准。

@拉西科尔,不,那是乔达。等价的java.time.format类称为DateTimeFormatter。

@阿伦,我已经编辑了答案,看看这个吧。

如果您可以使用外部库,那么ApacheCommonDateUtils提供了许多实用程序类,您可以使用它们来处理日期。为了将字符串解析为对象,可以使用以下示例:

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

这个功能现在内置于Java 8和以后,在JavaTimes类中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值