java与数据库交互时,有时需要按需选择相应的时间格式。

java与时间相关的类有Datetime Calendar timestamp。

其中Datetime 的打印格式为Mon Mar 12 22:59:49 CST 2018
Calendar的打印格式为java.util.GregorianCalendar[time=1520866789750,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2018,MONTH=2,WEEK_OF_YEAR=11,WEEK_OF_MONTH=3,DAY_OF_MONTH=12,DAY_OF_YEAR=71,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=59,SECOND=49,MILLISECOND=750,ZONE_OFFSET=28800000,DST_OFFSET=0]
timestamp的打印格式为 2018-03-12 22:59:49.722

timestamp与date的转换(通过unix时间戳)


Date date=new Date();
Timestamp timestamp=new Timestamp(date.getTime());
Date date1=new Date(timestamp.getTime());

date与calendar的转换


Calendar calendar=Calendar.getInstance();
calendar.setTime(date);
Date date2=calendar.getTime();

timestamp与calendar的转换


Timestamp timestamp1=new Timestamp(calendar.getTime().getTime());
Calendar calendar1=Calendar.getInstance();
calendar1.setTime(timestamp1);