您的位置:首页 > 编程语言 > Java开发

java时间日期操作

2016-11-27 13:41 330 查看
时间日期类:



package org;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

public Date getFormatDate(String date){
try {
return sdf.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 格式化时间日期
* @return
*/
public String getFormatDate(){
Date d = new Date();
return sdf.format(d);
}
/**
* 获取当前的时间: xxxx年xx月xx日	xx:xx:xx
* @return
*/
public String getCurrentDate(){
return cal.get(Calendar.YEAR) + "年" + (cal.get(Calendar.MONTH)+1) + "月" + cal.get(Calendar.DAY_OF_MONTH) + "日  " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE )+ ":" + cal.get(Calendar.SECOND);
}
/**
* 获取当前分钟中的秒
* @return
*/
public  int getMillion(){
return cal.get(Calendar.SECOND);
}
/**
* 获取当前小时中的分钟
* @return
*/
public int getMinute(){
return cal.get(Calendar.MINUTE);
}
/**
* 获取当天的第几个小时
* @return
*/
public int getHour(){
return cal.get(Calendar.HOUR_OF_DAY);

}
/**
* 获取当前月中的第几天
* @return
*/
public int getDay(){
return cal.get(Calendar.DAY_OF_MONTH);
}
/**
* 获取当前的月份
* @return
*/
public int getMonth(){
return (cal.get(Calendar.MONTH)+1);
}
/**
* 获取当前的年份
* @return
*/
public int getYear(){
return cal.get(Calendar.YEAR);
}

/**
* 获取某月的第几个周
* @return int
*/
public int getWeekOfMonth(){
return cal.WEEK_OF_MONTH;
}

/**
* 获取当前的时间毫秒数
* @return
*/
public long getCurrenTimeMillis(){
return System.currentTimeMillis();
}
}
Main 方法:
public static void main(String[] args) {
DateUtil d = new DateUtil();

System.out.println("字符串转换当前的时间是:"+d.getFormatDate("2016-11-27 12:45:07"));
System.out.println("当前的时间是:"+d.getFormatDate());
System.out.println("获取当前的时间:"+d.getCurrentDate());
System.out.println(new Date(d.getCurrenTimeMillis()));
System.out.println("获取某月的第几个星期:"+d.getWeekOfMonth());
System.out.println("获取当前时间的毫秒数:"+d.getCurrenTimeMillis()+" ms");
}
打印的结果集:

字符串转换当前的时间是:Sun Nov 27 12:45:07 GMT+08:00 2016

当前的时间是:2016-11-27 12:50:33

获取当前的时间:2016年11月27日  12:50:33

Sun Nov 27 12:50:33 GMT+08:00 2016

获取某月的第几个星期:4

获取当前时间的毫秒数:1480222233392 ms





简单的DateFormat格式代码:

要指定时间格式,使用时间模式字符串,在这个模式中,所有的ASCII字母被保留为模式字母。
定义如下:
Character描述Example
GEra designatorAD
yYear in four digits2001
MMonth in yearJuly or 07
dDay in month10
hHour in A.M./P.M. (1~12)12
HHour in day (0~23)22
mMinute in hour30
sSecond in minute55
SMillisecond234
EDay in weekTuesday
DDay in year360
FDay of week in month2 (second Wed. in July)
wWeek in year40
WWeek in month1
aA.M./P.M. markerPM
kHour in day (1~24)24
KHour in A.M./P.M. (0~11)10
zTime zoneEastern Standard Time
'Escape for textDelimiter
"Single quote`
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息