Java中日期类操作算法大全

    1.计算某一月份的最大天数
 
2.calendar和date的转化
<p style="text-indent: 2em;"> 3.格式化输出日期时间 (这个用的比较多)
<p style="text-indent: 2em;">其一 4.计算一年中的第几星期
<p style="text-indent: 2em;">  
5.add()和roll()的用法(不太常用)
<p style="text-indent: 2em;"> 
<p style="text-indent: 2em;"> 7. string 和 date ,long 之间相互转换 (最常用)
8. 通过时间求时间
<p style="text-indent: 2em;"> 9. java 和 具体的数据库结合
<p style="text-indent: 2em;">  <table border="1" cellspacing="0" cellpadding="2" width="400" align="center"><tbody><tr><td class="code" style="font-size: 9pt;"><pre>class datetest{*method 将字符串类型的日期转换为一个timestamp(时间戳记java.sql.timestamp)*@param datestring 需要转换为timestamp的字符串*@return datatime timestamppublic 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 datepublic 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();}}}</pre></td></tr></tbody></table> 

你可能感兴趣的:(java,工作)