Java 使用simpleDateFormat将字符串转换为Util Date不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18996834/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:12:25  来源:igfitidea点击:

Convert String to Util Date using simpleDateFormat not working

javadatedate-format

提问by madhu

I'm having a String having date in it, I need hh:mm:ss to be added to the date, but when i use dateFormat it gives me ParseException. Here is the code:

我有一个包含日期的字符串,我需要将 hh:mm:ss 添加到日期中,但是当我使用 dateFormat 时,它给了我 ParseException。这是代码:

DateFormat sdff = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String startDate = "2013-09-25";
Date frmDate;
frmDate = sdff.parse(startDate);

System.out.println("from date = " + frmDate);

I get parse exception for the abv code. But if i remove the hh:mm:ss from the Date format it works fine and the output will be from date = Wed Sep 25 00:00:00 IST 2013. But I need output like from date = 2013-09-25 00:00:00

我得到 abv 代码的解析异常。但是,如果我从 Date 格式中删除 hh:mm:ss 它工作正常,输出将来自 date = Wed Sep 25 00:00:00 IST 2013。但我需要从 date = 2013-09-25 00:00:00 开始的输出

Please help me. Thanks in advance.

请帮我。提前致谢。

采纳答案by SudoRahul

You'll need 2 SimpleDateFormat objects for that. One to parse your current date string and the other to format that parsed date to your desired format.

为此,您需要 2 个 SimpleDateFormat 对象。一个解析您当前的日期字符串,另一个将解析的日期格式化为您想要的格式。

// This is to parse your current date string
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startDate = "2013-09-25";
Date frmDate = sdf.parse(startDate); // Handle the ParseException here

// This is to format the your current date to the desired format
DateFormat sdff = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String frmDateStr = sdff.format(frmDate);

Edit:-

编辑:-

Datedoesn't have a format as such. You can only get a String representation of it using the SDF. Here an excerpt from the docs

Date没有这样的格式。您只能使用 SDF 获得它的字符串表示形式。这是文档的摘录

A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.

毫秒值的薄包装器,允许 JDBC 将其标识为 SQL DATE 值。毫秒值表示自 1970 年 1 月 1 日 00:00:00.000 GMT 以来经过的毫秒数。

And regarding your problem to insert it in the DB, java Datecan be as such persisted in the DB date format. You don't need to do any formatting. Only while fetching the date back from DB, you can use the to_char()method to format it.

关于将其插入数据库的问题,javaDate可以以数据库日期格式保存。您无需进行任何格式化。只有在从数据库取回日期时,您才能使用该to_char()方法对其进行格式化。

回答by Gaurav Varma

It is because your string is yyyy-MM-dd, but the date format u defined is yyyy-MM-dd hh:mm:ss. If you change your string startDate to yyyy-MM-dd hh:mm:ssit should work

这是因为您的字符串是yyyy-MM-dd,但您定义的日期格式是yyyy-MM-dd hh:mm:ss. 如果您将字符串 startDate 更改为yyyy-MM-dd hh:mm:ss它应该可以工作

回答by Prabhaker A

parse()is used to convert Stringto Date.It requires the formats to be matched otherwise you will get exception.
format()is used convert the date into date/time string.
Accroding to your requirement you need to use above two methods.

parse()用于转换String为 .Date它需要匹配格式,否则您将获得异常。
format()用于将日期转换为日期/时间字符串。
根据您的要求,您需要使用以上两种方法。

    DateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
    DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    String startDate = "2013-09-25";
    Date parsedDate = parser.parse(startDate);
    String formattedDate = dateFormatter.format(parsedDate);//this will give your expected output

回答by ThilinaMD

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.parse(sdf.format(new Date()));

This will return a Date type

这将返回一个日期类型

回答by Basil Bourque

tl;dr

tl;博士

LocalDate.parse( "2013-09-25" )       // Parse the string as a date-only object lacking time-of-day and lacking time zone.
.atStartOfDay(                        // Let java.time determine the first moment of the day. Not always 00:00:00 because of anomalies such as Daylight Saving Time (DST). 
    ZoneId.of( "America/Montreal" )   // Specify a time zone using legitimate `continent/region` name rather than 3-4 letter pseudo-zones.
)                                     // Returns a `ZonedDateTime` object.
.toString()                           // Generate a string in standard ISO 8601 format, wisely extended from the standard by appending the name of the time zone in square brackets.

2013-09-25T00:00-04:00[America/Montreal]

2013-09-25T00:00-04:00[美国/蒙特利尔]

To generate your string, pass a DateTimeFormatter.

要生成您的字符串,请传递一个DateTimeFormatter.

LocalDate.parse( "2013-09-25" )            // Parse the string as a date-only object lacking time-of-day and lacking time zone.
.atStartOfDay(                             // Let java.time determine the first moment of the day. Not always 00:00:00 because of anomalies such as Daylight Saving Time (DST). 
    ZoneId.of( "America/Montreal" )        // Specify a time zone using legitimate `continent/region` name rather than 3-4 letter pseudo-zones.
)                                          // Returns a `ZonedDateTime` object.
.format(                                   // Generate a string representing the value of this `ZonedDateTime` object.
    DateTimeFormatter.ISO_LOCAL_DATE_TIME  // Formatter that omits zone/offset.
).replace( "T" , " " )                     // Replace the standard's required 'T' in the middle with your desired SPACE character.

2013-09-25 00:00:00

2013-09-25 00:00:00

Details

细节

Your formatting pattern must match your input, as pointed out by others. One formatter is needed for parsing strings, another for generating strings.

正如其他人指出的那样,您的格式模式必须与您的输入相匹配。解析字符串需要一个格式化程序,另一个用于生成字符串。

Also, you are using outmoded classes.

此外,您正在使用过时的课程。

java.time

时间

The modern approach uses the java.timeclasses that supplanted the troublesome old legacy date-time classes.

现代方法使用java.time类取代了麻烦的旧遗留日期时间类。

LocalDate

LocalDate

The LocalDateclass represents a date-only value without time-of-day and without time zone.

LocalDate级表示没有时间一天和不同时区的日期,唯一的价值。

You can parse a string to produce a LocalDate. The standard ISO 8601 formats are used in java.time by default. So no need to specify a formatting pattern.

您可以解析字符串以生成LocalDate. 默认情况下,java.time 中使用标准 ISO 8601 格式。所以不需要指定格式模式。

LocalDate ld = LocalDate.parse( "2013-09-25" ) ;

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.

时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

如果未指定时区,JVM 会隐式应用其当前默认时区。该默认值可能随时更改,因此您的结果可能会有所不同。最好将您想要/预期的时区明确指定为参数。

Specify a proper time zone namein the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as ESTor ISTas they are nottrue time zones, not standardized, and not even unique(!).

以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/regionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTIST

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM's current default time zone, ask for it and pass as an argument. If omitted, the JVM's current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtimeby any code in any thread of any app within the JVM.

如果您想使用 JVM 的当前默认时区,请询问它并作为参数传递。如果省略,则隐式应用 JVM 的当前默认值。最好是明确的,因为JVM 中任何应用程序的任何线程中的任何代码都可能在运行时随时更改默认值。

ZoneId z = ZoneId.systemDefault() ;  // Get JVM's current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

或指定日期。您可以通过数字设置月份,对于 1 月至 12 月,合理的编号为 1-12。

LocalDate ld = LocalDate.of( 2013 , 9 , 25 ) ;  // Years use sane direct numbering (2013 means year 2013). Months use sane numbering, 1-12 for January-December.

Or, better, use the Monthenum objects pre-defined, one for each month of the year. Tip: Use these Monthobjects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.

或者,更好的是使用Month预定义的枚举对象,一年中的每个月都有一个。提示:Month在整个代码库中使用这些对象而不仅仅是整数,以使您的代码更具自文档性、确保有效值并提供类型安全

LocalDate ld = LocalDate.of( 2013 , Month.SEPTEMBER , 25 ) ;

Formats

格式

If you want to get the first moment of the day for that date, apply a time zone. As mentioned above, a date and time-of-day require the context of a time zone or offset-from-UTC to represent a specific moment on the timeline.

如果您想获得该日期当天的第一个时刻,请应用时区。如上所述,日期和时间需要时区上下文或 UTC 偏移量来表示时间线上的特定时刻。

Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST)mean the day may start at another time such as 01:00:00. Let java.timedetermine the first moment of the day.

不要假设一天从 00:00:00 开始。夏令时 (DST)等异常意味着一天可能在另一个时间开始,例如 01:00:00。让java.time确定一天中的第一个时刻。

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ld.atZone( z ) ;

If you want output in the format shown in your Question, you can define your own format. I caution you against omitting the time zone or offset info from the resulting string unless you are absolutely certain the user can discern its meaning from the greater context.

如果您希望以问题中显示的格式输出,您可以定义自己的格式。我提醒您不要从结果字符串中省略时区或偏移量信息,除非您绝对确定用户可以从更大的上下文中辨别其含义。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = zdt.format( f ) ;


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

With a JDBC drivercomplying with JDBC 4.2or later, you may exchange java.timeobjects directly with your database. No need for strings or java.sql.* classes.

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

Where to obtain the java.time classes?

从哪里获得 java.time 类?

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 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by Dulith De Costa

The issue is '2013-09-25'date cannot be parsedto 'yyyy-MM-dd hh:mm:ss' date format. First you need to parsefollowing date into its matching patternwhich is 'yyyy-MM-dd'.

问题是'2013-09-25'日期无法解析为“ yyyy-MM-dd hh:mm:ss”日期格式。首先,您需要将以下日期解析为其匹配模式,即'yyyy-MM-dd'.

Once it is parsed to its correct pattern you can provide the date pattern you prefer which is 'yyyy-MM-dd hh:mm:ss'.

一旦将其解析为正确的模式,您就可以提供您喜欢的日期模式,即'yyyy-MM-dd hh:mm:ss'.

Now you can format the Dateand it will output the date as you preferred.

现在您可以格式化它Date,它会根据您的喜好输出日期。

SimpleDateFormatcan be used to achieve this outcome.

SimpleDateFormat可以用来达到这个结果。

Try this code.

试试这个代码。

    String startDate = "2013-09-25";
    DateFormat existingPattern = new SimpleDateFormat("yyyy-MM-dd");
    DateFormat newPattern = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    Date date = existingPattern.parse(startDate);
    String formattedDate = newPattern.format(date);
    System.out.println(formattedDate); //outputs: 2013-09-25 00:00:00