设置日期格式,然后将其转换为 Date from String-Java

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

Set date format and then convert it in Date from String- Java

javadatetype-conversiondate-formatsimpledateformat

提问by Just_another_developer

I am doing this to set a date format and then convert it into date datatype but it is not giving expected results.

我这样做是为了设置日期格式,然后将其转换为日期数据类型,但没有给出预期的结果。

 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
 DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
 String cur_date=dateFormat.format(new Date());
 myDb.setDOB(formatter.parse(cur_date));

Scenario is: I want current date to be converted in yyyy/mm/dd and then pass it in setDOB(Date date).

场景是:我希望当前日期在 yyyy/mm/dd 中转换,然后在 setDOB(Date date) 中传递它。

EDIT:Result addedResult is Tue Jan 01 00:08:00 IST 2013

编辑:结果添加结果是 IST 2013 年 1 月 1 日星期二 00:08:00

GUYS! I am not using 'mm',here I just mistakenly wrote mm in DateFormat it is also MM

伙计们!我没有使用'mm',在这里我只是错误地在 DateFormat 中写了 mm 它也是 MM

EDIT AGAINFirst I just used setDOB(new Date() ); but got formatting issue,

再次编辑首先我只是使用 setDOB(new Date() ); 但遇到格式问题,

then I used SimpleDateFormat.format to set yyyy/MM/dd but it returns String so used

然后我使用 SimpleDateFormat.format 来设置 yyyy/MM/dd 但它返回 String 所以使用

DateFormat.parse to convert it back into date type.

DateFormat.parse 将其转换回日期类型。

回答by mael

You're not using the same format. Case matters! "MM" is for months, "mm" is for minutes.

您没有使用相同的格式。案例很重要!“MM”代表月,“mm”代表分钟。

回答by Jayamohan

The issue is you MM in the format.

问题是你MM的格式。

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
DateFormat formatter = new SimpleDateFormat("yyyy/mm/dd");
  • MM is month
  • mm is minute
  • MM是月
  • mm 是分钟

Refer herefor the detailed formats. So it should have been,

有关详细格式,请参阅此处。所以应该是

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");

回答by MadProgrammer

+1 mael for spotting the format issue first, however...

+1 mael 首先发现格式问题,但是......

Dateis a container for the number of milliseconds since the epoch (Jan-1970-01-01 GMT), it does not care about the format of the values.

Date是自纪元(Jan-1970-01-01 GMT)以来毫秒数的容器,它不关心值的格式。

For example, the following...

例如,以下...

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date now = new Date();
String cur_date = dateFormat.format(now);

try {
    System.out.println("Now = " + now);
    System.out.println("cur_date = " + cur_date);
    System.out.println("dateFormat.parse(cur_date) = " + dateFormat.parse(cur_date));
} catch (ParseException exp) {
    exp.printStackTrace();
}

Outputs...

输出...

Now = Thu Aug 01 18:08:39 EST 2013
cur_date = 2013/08/01
dateFormat.parse(cur_date) = Thu Aug 01 00:00:00 EST 2013

So you can lose important data about the date by doing this...

因此,您可以通过执行此操作丢失有关日期的重要数据...

Leave formatting to when you want to display the value, not when you want to store it (if you can get away with it)

将格式保留在您想要显示值的时候,而不是在您想要存储它的时候(如果可以的话)

回答by Jon Skeet

It sounds like you're expecting a Dateto "know" its format. It doesn't. A Dateobject justcontains a number of milliseconds since the Unix epoch. It doesn't know about time zones, or calendars, or string formats. It's just a date.

听起来您希望Date“知道”它的格式。它没有。一个Date对象包含自 Unix 时代以来的毫秒数。它不知道时区、日历或字符串格式。这只是一个约会。

So your code should just be:

所以你的代码应该是:

myDb.setDOB(new Date());

... and then handle the formatting of that wherever you're displayingit.

...然后在任何显示它的地方处理它的格式。

回答by Hareesh

formatter.parse is used to parse the String Date, It returns Date Object. The date is representedas a Date object or as the milliseconds as example since January 1, 1970, 00:00:00 GMT. I am not getting what actually your doing. Date object is always represented as in the above format.

formatter.parse 用于解析字符串日期,它返回日期对象。日期表示为 Date 对象或毫秒,例如自19701 月 1 日 00:00:00 GMT以来的毫秒数。我不明白你在做什么。日期对象始终以上述格式表示。

回答by Basil Bourque

The Question and other Answers all use troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

问题和其他答案都使用麻烦的旧日期时间类,这些类现在是遗留的,被 java.time 类取代。

LocalDate

LocalDate

Apparently you want a date-only value.

显然你想要一个仅限日期的值。

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

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

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.

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

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" );  // Or "Asia/Kolkata" , "Pacific/Auckland" , etc.
LocalDate today = LocalDate.now( z );

Generating strings

生成字符串

To generate a string representing the value of that LocalDate, simply call toString(). That method generates a string in standard ISO 8601format.

要生成表示那个值的字符串LocalDate,只需调用toString(). 该方法生成标准ISO 8601格式的字符串。

String output = today.toString();

2017-01-23

2017-01-23

Your desired format is close to that, using slash characters in place of hyphens. I suggest sticking with the standard formats whenever possible. But if you insist, just replace the characters.

您所需的格式与此接近,使用斜杠字符代替连字符。我建议尽可能坚持使用标准格式。但如果你坚持,只需更换字符。

String output = today.toString().replace( "-" , "/" );

For other formats use the DateTimeFormatterclass. And be aware of that class' ability to automatically localize while generating a string.

对于其他格式,请使用DateTimeFormatter该类。并注意该类在生成字符串时自动本地化的能力。



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

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 Filip

You re using different date String patterns. MM is for months, mm is for minutes (see SimpleDateFormat API)

您正在使用不同的日期字符串模式。MM 是几个月,mm 是分钟(参见SimpleDateFormat API

Your setDOB is taking a Date object. I fail to see why you might want to format your date when giving it is as a parameter in your method call. Usually one formats a date when it needs to be rendered / stored somewhere.

您的 setDOB 正在使用 Date 对象。我不明白为什么在方法调用中将日期作为参数提供时,您可能想要格式化日期。通常,当需要在某处呈现/存储日期时,会格式化日期。