一些關於日期的操作

來源:互聯網
上載者:User

1.
字串轉換成時間及時間相減:
   SimpleDateFormat formatter = new SimpleDateFormat ("yyyy.MM.dd";
        //假定像2002.07.04的是合法日期其他都非法。
    String str="2002.07.04";
    ParsePosition pos = new ParsePosition(0);
    Date dt=formatter.parse(str,pos);
   if(dt!=null)
   {
     //是合法日期
   }
    else
   {
     //非法日期
   }

2
兩個日期相減
import java.util.*;
import java.text.*;
class a
{
public static void main(String[] args)
{
String s1 = "2003/08/15 17:15:30";
String s2 = "2002/09/14 14:18:37";
try{
SimpleDateFormat formatter = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss";

ParsePosition pos = new ParsePosition(0);
ParsePosition pos1 = new ParsePosition(0);
Date dt1=formatter.parse(s1,pos);
Date dt2=formatter.parse(s2,pos1);
System.out.println("dt1="+dt1);
System.out.println("dt2="+dt2);
long l = dt1.getTime() - dt2.getTime();

System.out.println("Hello World!="+l);
}catch(Exception e){
System.out.println("exception"+e.toString());
}

}
}

3
得到2個月後的日期:
import java.util.*;
import java.text.DateFormat;
public class test2
{
public static void main(String args[]) throws Exception
{
String date="2001/11/30";

DateFormat dateFormat =
DateFormat.getDateInstance(DateFormat.MEDIUM);
GregorianCalendar grc=new GregorianCalendar();
grc.setTime(new Date(date));

grc.add(GregorianCalendar.MONTH,2);
System.out.println("grc="+dateFormat.format(grc.getTime()));
}
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.