[英]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 19891989 年 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);
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
如果您还需要有关时间(小时、分钟、秒)的信息,请使用从
LocalDate
到LocalDateTime
的一些转换
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.在这里,您可以按照快速入门教程进行操作。
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.