Creating java date object from year,month,day

2019-01-06 13:56发布

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
Wed Jan 25 00:00:08 IST 1989

I am passing 25 12 1988 but I get 25 Jan 1989. Why?

6条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-06 14:17

java.time

Using java.time framework built into Java 8

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.parse("2015-12-22").atStartOfDay() //2015-12-22T00:00
查看更多
Anthone
3楼-- · 2019-01-06 14:18

See JavaDoc:

month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.

So, the month you set is the first month of next year.

查看更多
We Are One
4楼-- · 2019-01-06 14:24

That's my favorite way prior to Java 8:

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

I'd say this is a cleaner approach than:

calendar.set(year, month - 1, day, 0, 0);
查看更多
The star\"
5楼-- · 2019-01-06 14:28

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.

Here is a quick example using LocalDate from the Joda Time library:

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

Here you can follow a quick start tutorial.

查看更多
The star\"
6楼-- · 2019-01-06 14:30

Months are zero-based in Calendar. So 12 is interpreted as december + 1 month. Use

c.set(year, month - 1, day, 0, 0);  
查看更多
Root(大扎)
7楼-- · 2019-01-06 14:31

Make your life easy when working with dates, timestamps and durations. Use HalDateTime from

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.

查看更多
登录 后发表回答