Set Date in a single line

前端 未结 8 2110
一个人的身影
一个人的身影 2021-01-31 01:55

According to the Java API, the constructor Date(year, month, day) is deprecated. I know that I can replace it with the following code:

Calendar myCa         


        
相关标签:
8条回答
  • 2021-01-31 02:36

    Use the constructor Date(year,month,date) in Java 8 it is deprecated:

    Date date = new Date(1990, 10, 26, 0, 0);
    

    The best way is to use SimpleDateFormat

    DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    Date date = format.parse("26/10/1985");
    

    you need to import import java.text.SimpleDateFormat;

    0 讨论(0)
  • 2021-01-31 02:37

    Why don't you just write a simple utility method:

    public final class DateUtils {
        private DateUtils() {
        }
    
        public static Calendar calendarFor(int year, int month, int day) {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.YEAR, year);
            cal.set(Calendar.MONTH, month);
            cal.set(Calendar.DAY_OF_MONTH, day);
            return cal;
        }
    
        // ... maybe other utility methods
    }
    

    And then call that everywhere in the rest of your code:

    Calendar cal = DateUtils.calendarFor(2010, Calendar.MAY, 21);
    
    0 讨论(0)
提交回复
热议问题