Java 语言的Date(日期),Calendar(日历),DateFormat(日期格式)组成了Java标准的一个基本但是非常重要的部分。
Date与String互转详情:https://blog..net/fz13768884254/article/details/82415432
(1) Calendar转化为Date
Calendar cal=Calendar.getInstance();
Date date=cal.getTime();
(2) Date转化为Calendar
Date date=new Date();
Calendar cal=Calendar.getInstance();
cal.setTime(date);
Calendar中时间转换方法:
/**
* Returns a Date
object representing this
* Calendar
's time value (millisecond offset from the
* href="#Epoch">Epoch
").*
* @return a Date
representing the time value.
* @see #setTime(Date)
* @see #getTimeInMillis()
*/
public final Date getTime() {
return new Date(getTimeInMillis());
}
/**
* Sets this Calendar's time with the given Date
.
*
* Note: Calling setTime()
with
* Date(Long.MAX_VALUE)
or Date(Long.MIN_VALUE)
* may yield incorrect field values from get()
.
*
* @param date the given Date.
* @see #getTime()
* @see #setTimeInMillis(long)
*/
public final void setTime(Date date) {
setTimeInMillis(date.getTime());
}
/**
* Returns this Calendar's time value in milliseconds.
*
* @return the current time as UTC milliseconds from the epoch.
* @see #getTime()
* @see #setTimeInMillis(long)
*/
public long getTimeInMillis() {
if (!isTimeSet) {
updateTime();
}
return time;
}
/**
* Sets this Calendar's current time from the given long value.
*
* @param millis the new time in UTC milliseconds from the epoch.
* @see #setTime(Date)
* @see #getTimeInMillis()
*/
public void setTimeInMillis(long millis) {
// If we don't need to recalculate the calendar field values,
// do nothing.
if (time == millis && isTimeSet && areFieldsSet && areAllFieldsSet
&& (zone instanceof ZoneInfo) && !((ZoneInfo)zone).isDirty()) {
return;
}
time = millis;
isTimeSet = true;
areFieldsSet = false;
computeFields();
areAllFieldsSet = areFieldsSet = true;
}
public void getTimeByCalendar(){
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);//获取年份
int month=cal.get(Calendar.MONTH);//获取月份
int day=cal.get(Calendar.DATE);//获取日
int hour=cal.get(Calendar.HOUR);//小时
int minute=cal.get(Calendar.MINUTE);//分
int second=cal.get(Calendar.SECOND);//秒
int WeekOfYear = cal.get(Calendar.DAY_OF_WEEK);//一周的第几天
System.out.println("现在的时间是:公元"+year+"年"+month+"月"+day+"日 "+hour+"时"+minute+"分"+second+"秒 星期"+WeekOfYear);
}