How to get a Date object from year,month and day?

前端 未结 5 1149
孤街浪徒
孤街浪徒 2021-01-23 07:14

When I used the following code, the Date Object was wrong.

Date date = new Date(day.getYear(), day.getMonth(), day.getDay());

Can

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-23 07:20

    You can use the Calendar class to achieve this.

    public static void main(String[] args) throws Exception {
        Date date = new Date (115, 7, 5);
        System.out.println("date     = " + date);
    
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 5);
        calendar.set(Calendar.MONTH, 7);
        calendar.set(Calendar.YEAR, 2015);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        date = calendar.getTime();
        System.out.println("calendar = " + date);
    
        // or create directly a new clanedar instance
        // thanks Tom to mention this
        calendar = new GregorianCalendar(2015, 7, 5);
        date = calendar.getTime();
        System.out.println("calendar = " + date);
    }
    

    output

    date     = Wed Aug 05 00:00:00 CEST 2015
    calendar = Wed Aug 05 00:00:00 CEST 2015
    calendar = Wed Aug 05 00:00:00 CEST 2015
    

提交回复
热议问题