Creating java date object from year,month,day

前端 未结 6 1052
长情又很酷
长情又很酷 2020-11-27 14:50
int day = Integer.parseInt(request.getParameter(\"day\"));  // 25
int month = Integer.parseInt(request.getParameter(\"month\")); // 12
int year = Integer.parseInt(re         


        
相关标签:
6条回答
  • 2020-11-27 15:13

    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.

    0 讨论(0)
  • 2020-11-27 15:14

    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.

    0 讨论(0)
  • 2020-11-27 15:25

    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.

    0 讨论(0)
  • 2020-11-27 15:26

    That's my favorite way prior to Java 8:

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

    I'd say this is a cleaner approach than:

    calendar.set(year, month - 1, day, 0, 0);
    
    0 讨论(0)
  • 2020-11-27 15:33

    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
    
    0 讨论(0)
  • 2020-11-27 15:36

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

    c.set(year, month - 1, day, 0, 0);  
    
    0 讨论(0)
提交回复
热议问题