简体   繁体   English

从年,月,日创建java日期对象

[英]Creating java date object from year,month,day

int day = Integer.parseInt(request.getParameter("day"));  // 25
int month = Integer.parseInt(request.getParameter("month")); // 12
int year = Integer.parseInt(request.getParameter("year")); // 1988

System.out.println(year);

Calendar c = Calendar.getInstance();
c.set(year, month, day, 0, 0);  

b.setDob(c.getTime());

System.out.println(b.getDob());  

Output is:输出是:

1988 1988年
Wed Jan 25 00:00:08 IST 1989 1989 年 1 月 25 日星期三 00:00:08 IST

I am passing 25 12 1988 but I get 25 Jan 1989 .我正在通过25 12 1988但我得到25 Jan 1989 Why?为什么?

Months are zero-based in Calendar.月份在日历中从零开始。 So 12 is interpreted as december + 1 month.所以 12 被解释为 12 月 + 1 个月。 Use利用

c.set(year, month - 1, day, 0, 0);  

That's my favorite way prior to Java 8:这是我在 Java 8 之前最喜欢的方式:

Date date = new GregorianCalendar(year, month - 1, day).getTime();

I'd say this is a bit cleaner than:我会说这比:

calendar.set(year, month - 1, day, 0, 0);

java.time java.time

Using java.time framework built into Java 8使用 Java 8 中内置的java.time框架

int year = 2015;
int month = 12;
int day = 22;
LocalDate.of(year, month, day); //2015-12-22
LocalDate.parse("2015-12-22"); //2015-12-22
//with custom formatter 
DateTimeFormatter.ofPattern formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate.parse("22-12-2015", formatter); //2015-12-22

If you need also information about time(hour,minute,second) use some conversion from LocalDate to LocalDateTime如果您还需要有关时间(小时、分钟、秒)的信息,请使用从LocalDateLocalDateTime的一些转换

LocalDate.parse("2015-12-22").atStartOfDay() //2015-12-22T00:00

Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library. Java 的日历表示不是最好的,他们正在为 Java 8 开发它。我建议您使用Joda Time或其他类似的库。

Here is a quick example using LocalDate from the Joda Time library:这是一个使用 Joda Time 库中的 LocalDate 的快速示例:

LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();

Here you can follow a quick start tutorial.在这里,您可以按照快速入门教程进行操作。

See JavaDoc :请参阅JavaDoc

month - the value used to set the MONTH calendar field. month - 用于设置 MONTH 日历字段的值。 Month value is 0-based.月份值从 0 开始。 eg, 0 for January.例如,0 表示一月。

So, the month you set is the first month of next year.因此,您设置的月份是明年的第一个月。

Make your life easy when working with dates, timestamps and durations.使用日期、时间戳和持续时间让您的生活更轻松。 Use HalDateTime from使用 HalDateTime 从

http://sourceforge.net/projects/haldatetime/?source=directory http://sourceforge.net/projects/haldatetime/?source=directory

For example you can just use it to parse your input like this:例如,您可以使用它来解析您的输入,如下所示:

HalDateTime mydate = HalDateTime.valueOf( "25.12.1988" );
System.out.println( mydate );   // will print in ISO format: 1988-12-25

You can also specify patterns for parsing and printing.您还可以指定用于解析和打印的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM