Removing time from a Date object?

前端 未结 19 1266
余生分开走
余生分开走 2020-12-15 02:26

I want to remove time from Date object.

DateFormat df;
String date;
df = new SimpleDateFormat(\"dd/MM/yyyy\");
d = eventList.get(0).getStartDate         


        
19条回答
  •  温柔的废话
    2020-12-15 02:55

    A bit of a fudge but you could use java.sql.Date. This only stored the date part and zero based time (midnight)

    Calendar c = Calendar.getInstance();
    c.set(Calendar.YEAR, 2011);
    c.set(Calendar.MONTH, 11);
    c.set(Calendar.DATE, 5);
    java.sql.Date d = new java.sql.Date(c.getTimeInMillis());
    System.out.println("date is  " + d);
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    System.out.println("formatted date is  " + df.format(d));
    

    gives

    date is  2011-12-05
    formatted date is  05/12/2011
    

    Or it might be worth creating your own date object which just contains dates and not times. This could wrap java.util.Date and ignore the time parts of it.

提交回复
热议问题