欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java时间日期使用与查询代码详解

程序员文章站 2024-02-26 11:23:04
只要格式正确,直接比较字符串就可以了呀,精确到秒的也一样 string s1 = "2003-12-12 11:30:24"; string s...

只要格式正确,直接比较字符串就可以了呀,精确到秒的也一样

string  s1  =  "2003-12-12  11:30:24";  
 string  s2  =  "2004-04-01  13:31:40";  
 int  res  =  s1.compareto(s2);  

求日期差

simpledateformat  df  =  new  simpledateformat("yyyy-mm-dd  hh:mm:ss");  
 date  begin=df.parse("2004-01-02  11:30:24");  
 date  end  =  df.parse("2004-03-26  13:31:40");  
 long  between=(end.gettime()-begin.gettime())/1000;//除以1000是为了转换成秒  
 int  day=between/(24*3600);  
 int  hour=between%(24*3600)/3600;  
 int  minute=between%3600/60;  
 int  second=between%60; 

经常用到时间日期类,所以就将常用的日期方法和属性都归纳总结如下,方便大家查找

1.计算某一月份的最大天数

calendar time=calendar.getinstance(); 
time.clear(); 
time.set(calendar.year,year); 
time.set(calendar.month,i-1);//注意,calendar对象默认一月为0 
int day=time.getactualmaximum(calendar.day_of_month);//本月份的天数 

注:在使用set方法之前,最好先clear一下,否则很多信息会继承自系统当前时间

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

3.格式化输出日期时间

date date=new date(); 
simpledateformat df=new simpledateformat("yyyy-mm-dd hh:mm:ss"); 
system.out.println(df.format(date)); 

4.计算一年中的第几星期

(1)计算某一天是一年中的第几星期

calendar cal=calendar.getinstance(); 
cal.set(calendar.year, 2006); 
cal.set(calendar.month, 9); 
cal.set(calendar.day_of_month, 3); 
int weekno=cal.get(calendar.week_of_year); 

(2)计算一年中的第几星期是几号

simpledateformat df=new simpledateformat("yyyy-mm-dd"); 
calendar cal=calendar.getinstance(); 
cal.set(calendar.year, 2006); 
cal.set(calendar.week_of_year, 1); 
cal.set(calendar.day_of_week, calendar.monday); 
system.out.println(df.format(cal.gettime())); 

输出:

2006-01-02 

5.add()和roll()的用法
(1)add()方法

simpledateformat df=new simpledateformat("yyyy-mm-dd"); 
calendar cal=calendar.getinstance(); 
cal.set(calendar.year, 2006); 
cal.set(calendar.month, 9); 
cal.set(calendar.day_of_month, 3); 
cal.add(calendar.date, -4); 
date date=cal.gettime(); 
system.out.println(df.format(date)); 
cal.add(calendar.date, 4); 
date=cal.gettime(); 
system.out.println(df.format(date)); 

输出:
2006-08-30
2006-10-03

(2)roll方法

cal.set(calendar.year, 2006); 
cal.set(calendar.month, 9); 
cal.set(calendar.day_of_month, 3); 
cal.roll(calendar.date, -4); 
date=cal.gettime(); 
system.out.println(df.format(date)); 
cal.roll(calendar.date, 4); 
date=cal.gettime(); 
system.out.println(df.format(date)); 

输出:

2006-10-29

2006-10-03

可见,roll()方法在本月内循环,一般使用add()方法;

6.计算两个任意时间中间的间隔天数

(1)传进calendar对象

/** */
/**计算两个时间之间相隔天数 
* @param startday 开始时间 
* @param endday 结束时间 
* @return 
*/
public int getintervaldays(calendar startday,calendar endday)...{
	//确保startday在endday之前 
	if(startday.after(endday))...{
		calendar cal=startday;
		startday=endday;
		endday=cal;
	}
	//分别得到两个时间的毫秒数 
	long sl=startday.gettimeinmillis();
	long el=endday.gettimeinmillis();
	long ei=el-sl;
	//根据毫秒数计算间隔天数 
	return (int)(ei/(1000*60*60*24));
}

(2)传进date对象

/** */
/**计算两个时间之间相隔天数 
* @param startday 开始时间 
* @param endday 结束时间 
* @return 
*/
public int getintervaldays(date startday,date endday)...{
	//确保startday在endday之前 
	if(startday.after(endday))...{
		date cal=startday;
		startday=endday;
		endday=cal;
	}
	//分别得到两个时间的毫秒数 
	long sl=startday.gettime();
	long el=endday.gettime();
	long ei=el-sl;
	//根据毫秒数计算间隔天数 
	return (int)(ei/(1000*60*60*24));
}

同理,可以用相同的方法计算出任意两个时间相隔的小时数,分钟数,秒钟数等
注:以上方法是完全按时间计算,有时并不能令人满意,如:

startday="2006-10-11 20:00:00" 
endday="2006-10-12 8:00:00" 

计算结果为0,但是我们也许相让计算结果变为1,此时可以用如下方法实现:
在传参之前,先设定endday的时间,如:

endday.set(calendar.hour_of_day, 23); 
endday.set(calendar.minute, 59); 
endday.set(calendar.second, 59); 
endday.set(calendar.millisecond, 59); 

这样再传进去startday,endday,则结果就如我们所愿了。不过,如果嫌以上方法麻烦,可以参考以下方法:
(3)改进精确计算相隔天数的方法

public int getdaysbetween (calendar d1, calendar d2) ...{
	if (d1.after(d2)) ...{
		// swap dates so that d1 is start and d2 is end 
		java.util.calendar swap = d1;
		d1 = d2;
		d2 = swap;
	}
	int days = d2.get(calendar.day_of_year) - d1.get(calendar.day_of_year);
	int y2 = d2.get(calendar.year);
	if (d1.get(calendar.year) != y2) ...{
		d1 = (calendar) d1.clone();
		do ...{
			days += d1.getactualmaximum(calendar.day_of_year);
			//得到当年的实际天数 
			d1.add(calendar.year, 1);
		}
		while (d1.get(calendar.year) != y2);
	}
	return days;
}

获取系统当前时间:

public static string getsystemtime(){
	date date=new date();
	simpledateformat df=new simpledateformat("yyyy-mm-dd hh:mm:ss");
	return df.format(date);
}
//字符串转化成时间类型(字符串可以是任意类型,只要和simpledateformat中的格式一致即可) 
java.text.simpledateformat sdf = new java.text.simpledateformat("m/dd/yyyy hh:mm:ss a",java.util.locale.us);
java.util.date d = sdf.parse("5/13/2003 10:31:37 am");
simpledateformat formatter = new simpledateformat("yyyy-mm-dd hh:mm:ss");
string mdatetime1=formatter.format(d);
//当前时间 
calendar cal = calendar.getinstance();
// simpledateformat formatter = new simpledateformat("yyyy-mm-dd hh:mm:ss"); 
simpledateformat formatter = new simpledateformat("yyyy-mm-dd hh:mm:ss g e d f w w a e f");
string mdatetime=formatter.format(cal.gettime());
//1年前日期 
java.util.date mydate=new java.util.date();
long mytime=(mydate.gettime()/1000)-60*60*24*365;
mydate.settime(mytime*1000);
string mdate=formatter.format(mydate);
//明天日期 
mydate=new java.util.date();
mytime=(mydate.gettime()/1000)+60*60*24;
mydate.settime(mytime*1000);
mdate=formatter.format(mydate);
//两个时间之间的天数 
simpledateformat myformatter = new simpledateformat("yyyy-mm-dd");
java.util.date date= myformatter.parse("2003-05-1");
java.util.date mydate= myformatter.parse("1899-12-30");
long day=(date.gettime()-mydate.gettime())/(24*60*60*1000);
//加半小时 
simpledateformat format = new simpledateformat("yyyy-mm-dd hh:mm:ss");
java.util.date date1 = format.parse("2002-02-28 23:16:00");
long time=(date1.gettime()/1000)+60*30;
date1.settime(time*1000);
string mydate1=formatter.format(date1);
//年月周求日期 
simpledateformat formatter2 = new simpledateformat("yyyy-mm f e");
java.util.date date2= formatter2.parse("2003-05 5 星期五");
simpledateformat formatter3 = new simpledateformat("yyyy-mm-dd");
string mydate2=formatter3.format(date2);
//求是星期几 
mydate= myformatter.parse("2001-1-1");
simpledateformat formatter4 = new simpledateformat("e");
string mydate3=formatter4.format(mydate);

在开发web应用中,针对不同的数据库日期类型,我们需要在我们的程序中对日期类型做各种不同的转换。若对应数据库数据是oracle的date类型,即只需要年月日的,可以选择使用java.sql.date类型,若对应的是mssqlserver数据库的datetime类型,即需要年月日时分秒的,选择java.sql.timestamp类型

你可以使用dateformat定义时间日期的格式,转一个字符串即可

package personal.jessica;
import java.util.date;
import java.util.calendar;
import java.sql.timestamp;
import java.text.dateformat;
import java.text.simpledateformat;
import java.util.locale;
class datetest{
	/** 
*method 将字符串类型的日期转换为一个timestamp(时间戳记java.sql.timestamp) 
*@param datestring 需要转换为timestamp的字符串 
*@return datatime timestamp 
*/
	public final static java.sql.timestamp string2time(string datestring)  
	throws java.text.parseexception {
		dateformat dateformat;
		dateformat = new simpledateformat("yyyy-mm-dd kk:mm:ss.sss", locale.english);
		//设定格式  
		//dateformat = new simpledateformat("yyyy-mm-dd kk:mm:ss", locale.english);  
		dateformat.setlenient(false);
		java.util.date timedate = dateformat.parse(datestring);
		//util类型  
		java.sql.timestamp datetime = new java.sql.timestamp(timedate.gettime());
		//timestamp类型,timedate.gettime()返回一个long型  
		return datetime;
	}
	/** 
*method 将字符串类型的日期转换为一个date(java.sql.date) 
*@param datestring 需要转换为date的字符串 
*@return datatime date 
*/
	public final static java.sql.date string2date(string datestring)  
	throws java.lang.exception {
		dateformat dateformat;
		dateformat = new simpledateformat("yyyy-mm-dd", locale.english);
		dateformat.setlenient(false);
		java.util.date timedate = dateformat.parse(datestring);
		//util类型  
		java.sql.date datetime = new java.sql.date(timedate.gettime());
		//sql类型  
		return datetime;
	}
	public static void main(string[] args){
		date da = new date();
		//注意:这个地方da.gettime()得到的是一个long型的值  
		system.out.println(da.gettime());
		//由日期date转换为timestamp  
		//第一种方法:使用new timestamp(long)  
		timestamp t = new timestamp(new date().gettime());
		system.out.println(t);
		//第二种方法:使用timestamp(int year,int month,int date,int hour,int minute,int second,int nano)  
		timestamp tt = new timestamp(calendar.getinstance().get(  
		calendar.year) - 1900, calendar.getinstance().get(  
		calendar.month), calendar.getinstance().get(  
		calendar.date), calendar.getinstance().get(  
		calendar.hour), calendar.getinstance().get(  
		calendar.minute), calendar.getinstance().get(  
		calendar.second), 0);
		system.out.println(tt);
		try {
			string stodate = "2005-8-18";
			//用于转换成java.sql.date的字符串  
			string stotimestamp = "2005-8-18 14:21:12.123";
			//用于转换成java.sql.timestamp的字符串  
			date date1 = string2date(stodate);
			timestamp date2 = string2time(stotimestamp);
			system.out.println("date:"+date1.tostring());
			//结果显示  
			system.out.println("timestamp:"+date2.tostring());
			//结果显示
		}
		catch(exception e) {
			e.printstacktrace();
		}
	}
}

下面是例子:

java代码

package test;
import java.text.dateformat;
import java.text.parseexception;
import java.text.simpledateformat;
import java.util.calendar;
import java.util.date;
import java.util.hashtable;
import javax.swing.joptionpane;
public class test2{
	public static boolean isdate(string s){
		string a[]=s.split("-");
		boolean flg=true;
		if(!(integer.parseint(a[0])>=1950 && integer.parseint(a[0])<=2050)){
			flg=false;
		}
		return flg;
	}
	public static boolean checkdate(string s){
		boolean ret = true;
		try{
			dateformat df = new simpledateformat("yyyy-mm-dd");
			ret = df.format(df.parse(s)).equals(s);
		}
		catch(parseexception e){
			ret = false;
		}
		return ret;
	}
	public object dateinfo(string s){
		string a[]=s.split("-",2);
		hashtable fest =new hashtable();
		fest.put("01-01","元旦节");
		fest.put("02-14","情人节");
		fest.put("03-12","植树节");
		fest.put("03-15","消费者节");
		fest.put("04-01","愚人节");
		fest.put("04-05","清明节");
		fest.put("05-01","劳动节");
		fest.put("06-01","儿童节");
		fest.put("07-01","建党节");
		fest.put("08-01","建军节");
		fest.put("09-10","教师节");
		fest.put("10-01","国庆节");
		fest.put("12-25","圣诞节");
		if(fest.containskey(a[1])){
			return fest.get(a[1]);
		} else{
			return "无节日";
		}
	}
	public string xingzuo(date s){
		calendar cal = calendar.getinstance();
		cal.settime(s);
		string xingzuo="无";
		int day=cal.get(calendar.day_of_year);
		if((cal.get(calendar.year)%4==0)&&(cal.get(calendar.year)%100!=0)||(cal.get(calendar.year)%400==0)){
			if((day>=1 &&day<=19)||(day>=357&&day<=366)){
				xingzuo= "魔蝎座";
			} else if(day>=20 &&day<=49){
				xingzuo= "水瓶座";
			} else if(day>=50 &&day<=80){
				xingzuo= "双鱼座";
			} else if(day>=81 &&day<=110){
				xingzuo= "白羊座";
			} else if(day>=111 &&day<=141){
				xingzuo= "金牛座";
			} else if(day>=142 &&day<=173){
				xingzuo= "双子座";
			} else if(day>=174 &&day<=203){
				xingzuo= "巨蟹座";
			} else if(day>=204 &&day<=235){
				xingzuo= "狮子座";
			} else if(day>=236 &&day<=266){
				xingzuo= "处女座";
			} else if(day>=267 &&day<=296){
				xingzuo= "天秤座";
			} else if(day>=297 &&day<=326){
				xingzuo= "天蝎座";
			} else if(day>=327 &&day<=356){
				xingzuo= "射手座";
			}
		} else{
			if((day>=1 &&day<=19)||(day>=357&&day<=366)){
				xingzuo= "魔蝎座";
			} else if(day>=20 &&day<=48){
				xingzuo= "水瓶座";
			} else if(day>=49 &&day<=79){
				xingzuo= "双鱼座";
			} else if(day>=80 &&day<=109){
				xingzuo= "白羊座";
			} else if(day>=110 &&day<=140){
				xingzuo= "金牛座";
			} else if(day>=141 &&day<=172){
				xingzuo= "双子座";
			} else if(day>=173 &&day<=202){
				xingzuo= "巨蟹座";
			} else if(day>=203 &&day<=234){
				xingzuo= "狮子座";
			} else if(day>=235 &&day<=265){
				xingzuo= "处女座";
			} else if(day>=266 &&day<=295){
				xingzuo= "天秤座";
			} else if(day>=296 &&day<=325){
				xingzuo= "天蝎座";
			} else if(day>=326 &&day<=355){
				xingzuo= "射手座";
			}
		}
		return xingzuo;
	}
	public date parsedate(string s){
		simpledateformat bartdateformat = new simpledateformat("yyyy-mm-dd");
		try {
			date date3 = bartdateformat.parse(s);
			date3=bartdateformat.parse(s);
			return date3;
		}
		catch (exception ex) {
			return null;
		}
	}
	public static void main(string[] args) {
		calendar cal = calendar.getinstance();
		test2 test2=new test2();
		string date1=joptionpane.showinputdialog("请你输入日期,格式如2000-10-15");
		while(!(test2.checkdate(date1)&&test2.isdate(date1))){
			date1=joptionpane.showinputdialog("请你输入日期,格式如2000-10-15");
		}
		simpledateformat bartdateformat1 = new simpledateformat("yyyy,mm,dd,eeee");
		simpledateformat bartdateformat2 = new simpledateformat("yyyy-mm-dd");
		date date2=test2.parsedate(date1);
		string festinfo=(string)test2.dateinfo(date1);
		system.out.println(bartdateformat1.format(date2) +","+ festinfo+","+ test2.xingzuo(date2));
		string day=joptionpane.showinputdialog("请你输入要查询n天后的日期信息");
		cal.settime(date2);
		cal.add(calendar.date, integer.parseint(day));
		string date5=bartdateformat2.format(cal.gettime());
		festinfo=(string)test2.dateinfo(date5);
		system.out.println(bartdateformat1.format(cal.gettime())+","+ festinfo+","+ test2.xingzuo(cal.gettime()));
	}
}

总结

以上就是本文关于java时间日期使用与查询代码详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!