java中String Date相互轉換

1.字符串轉換成日期類型 java

SimpleDateFormat sdf=newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dstr="2013-6-13 12:34:23";
try{
Date date=sdf.parse(dstr);
System.out.println(date);//Thu Jun 13 12:34:23 CST 2013
} catch(ParseException e) {
e.printStackTrace();
}  

2.日期轉換成字符串ide

SimpleDateFormat sdf=newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=newDate();
String str=sdf.format(date);
System.out.println(str);//2013-09-22 21:51:29

3.取得前一天的時間orm

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
String yesterday =
newSimpleDateFormat( "yyyy-MM-dd HH:mm:ss ").format(cal.getTime());
System.out.println(yesterday);
//當前系統時間爲2013年9月22日,輸入前一天的時間是2013-09-21 21:54:19


程序示例:字符串

packagedate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public classTest {
  //判斷字符串是不是日期格式
  public boolean isDateAvailable(String str){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try{
      sdf.parse(str);
      return true;
    } catch(ParseException e) {
      return false;
    }
  }
  public static void main(String[] args){
    Test t = newTest();
    String begin = "2013-6-13 12:34:23";
    String end = "2013-8-13 12:34:23";
    if(t.isDateAvailable(begin)&& t.isDateAvailable(end)){
      try{
        Date d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(begin);
        Date d2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(end);
        System.out.println(d1.before(d2));
      } catch(ParseException e) {
        e.printStackTrace();
      }
    }
  }
}
相關文章
相關標籤/搜索