Calendar和Date互转
(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 <code>Date</code> object representing this
* <code>Calendar</code>'s time value (millisecond offset from the <a
* href="#Epoch">Epoch</a>").
*
* @return a <code>Date</code> 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 <code>Date</code>.
* <p>
* Note: Calling <code>setTime()</code> with
* <code>Date(Long.MAX_VALUE)</code> or <code>Date(Long.MIN_VALUE)</code>
* may yield incorrect field values from <code>get()</code>.
*
* @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);
}
Java中Date,Long,String三种类型间的互相转化
Date date = new Date();//获取当前时间
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1.将date型的数据转换成特定的String型字符串
String sDate=df.format(date);
2.把String型的字符串转换成特定格式的date类型
String sDate="2001.12.12-08.23.21";
df = new SimpleDateFormat("yyyy.MM.dd-HH.mm.ss");
try {
Date d = df.parse(dStr);
} catch (ParseException pe) {
System.out.println(pe.getMessage());
}
3.Date转long型
Date date = new Date();
long dateTime = date.getTime();
4.long型转Date
long dateTime = 14830682769461;
Date date = new Date(dateTime);
System.out.println(date.toString());