先看例子:
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class DateTest { public static void main(String[] args) { Date date = new Date(); System.out.println("Today**********"); printDate(date); GregorianCalendar d = new GregorianCalendar(); d.add(Calendar.DAY_OF_MONTH, -1); Date yesterDate = d.getTime(); System.out.println("Yesterday**********"); printDate(yesterDate); } private static void printDate(Date date) { System.out.printf("epoch毫秒数: %s%n", date.getTime()); System.out.printf("LONG Date: %s%n", DateFormat.getDateInstance(DateFormat.LONG)); System.out.printf("SHORT Date: %s%n", DateFormat.getDateInstance(DateFormat.SHORT)); System.out.printf("LONG Time: %s%n", DateFormat.getTimeInstance(DateFormat.LONG)); System.out.printf("SHORT Time: %s%n", DateFormat.getTimeInstance(DateFormat.SHORT)); System.out.printf("LONG DateTime: %s%n", DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG)); System.out.printf("SHORT DateTime: %s%n", DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.printf("指定格式: %s%n", df.format(date)); } }
输出:
Today********** epoch毫秒数: 1534952854644 LONG Date: java.text.SimpleDateFormat@a87fc158 SHORT Date: java.text.SimpleDateFormat@d5391ab7 LONG Time: java.text.SimpleDateFormat@787e63cb SHORT Time: java.text.SimpleDateFormat@58715d3 LONG DateTime: java.text.SimpleDateFormat@a0ba3d93 SHORT DateTime: java.text.SimpleDateFormat@b5341f2a 指定格式: 2018-08-22 23:47:34 Yesterday********** epoch毫秒数: 1534866454874 LONG Date: java.text.SimpleDateFormat@a87fc158 SHORT Date: java.text.SimpleDateFormat@d5391ab7 LONG Time: java.text.SimpleDateFormat@787e63cb SHORT Time: java.text.SimpleDateFormat@58715d3 LONG DateTime: java.text.SimpleDateFormat@a0ba3d93 SHORT DateTime: java.text.SimpleDateFormat@b5341f2a 指定格式: 2018-08-21 23:47:34