服务器之家

服务器之家 > 正文

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

时间:2021-02-23 11:33     来源/作者:adayabetter

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

java" id="highlighter_301180">
?
1
2
3
String  s1  =  "2003-12-12  11:30:24"
 String  s2  =  "2004-04-01  13:31:40"
 int  res  =  s1.compareTo(s2);

日期

?
1
2
3
4
5
6
7
8
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.计算某一月份的最大天数

?
1
2
3
4
5
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

?
1
2
Calendar cal=Calendar.getInstance();
Date date=cal.getTime();

(2) Date转化为Calendar

?
1
2
3
Date date=new Date();
Calendar cal=Calendar.getInstance();
cal.setTime(date);

3.格式化输出日期时间

?
1
2
3
Date date=new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(df.format(date));

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

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

?
1
2
3
4
5
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)计算一年中的第几星期是几号

?
1
2
3
4
5
6
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()));

输出:

?
1
2006-01-02

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

?
1
2
3
4
5
6
7
8
9
10
11
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方法

?
1
2
3
4
5
6
7
8
9
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对象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/** */
/**计算两个时间之间相隔天数
* @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对象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/** */
/**计算两个时间之间相隔天数
* @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));
}

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

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

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

?
1
2
3
4
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)改进精确计算相隔天数的方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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;
}

获取系统当前时间:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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定义时间日期的格式,转一个字符串即可

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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时间日期使用与查询代码详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

原文链接:http://blog.csdn.net/adayabetter/article/details/44596597

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部