java calendar与date_JAVA中Calendar与Date类型互转

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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值