package Rong;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test{
      //将指定日期转化为秒数
      public static int getSecondsFromDate(String expireDate){
              if(expireDate==null||expireDate.trim().equals(""))
                      return 0;
              SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
              Date date=null;
              try{
                      date=sdf.parse(expireDate);
                      return (int)(date.getTime()/1000);
                      }
              catch(ParseException e)
              {
                      e.printStackTrace();
                      return 0;
                      }
              }
      //秒数转化为日期
      public static String getDateFromSeconds(String seconds){
              if(seconds==null)
                      return " ";
              else{
                      Date date=new Date();
                      try{
                              date.setTime(Long.parseLong(seconds)*1000);
                              }
                      catch(NumberFormatException nfe){
                              nfe.printStackTrace();
                              return "Input string:"+seconds+"not correct,eg:2011-01-20";
                              }
                      SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                      return sdf.format(date);
                      }
              }
      //检查输入的日期格式是否正确
      public static boolean checkDate(String date){
              String DatePattern = "^(?:([0-9]{4}-(?:(?:0?[1,3-9]|1[0-2])-(?:29|30)|"
                            + "((?:0?[13578]|1[02])-31)))|"
                            + "([0-9]{4}-(?:0?[1-9]|1[0-2])-(?:0?[1-9]|1\\d|2[0-8]))|"
                            + "(((?:(\\d\\d(?:0[48]|[2468][048]|[13579][26]))|"
                            + "(?:0[48]00|[2468][048]00|[13579][26]00))-0?2-29)))$";
              Pattern p=Pattern.compile(DatePattern);
              Matcher m=p.matcher(date);
              boolean b=m.matches();
              return b;             
      }
     
      public static void  main(String[] arg0){
              System.out.println("请输入日期(年月日,格式如:1970-01-01)");
              Scanner s=new Scanner(System.in);
              String t=s.next();
              if(checkDate(t)){
                      System.out.println("1970年1月1日到"+t+"的秒数为:");
                      int i=Test.getSecondsFromDate(t);
                      System.out.println(i);
                     
                      System.out.println("再由秒数转换为日期:");
                      String str=Test.getDateFromSeconds(String.valueOf(i));
                      System.out.println(str);
              }
              else{
                      System.out.println("您输入的日期格式不正确!");
              }
              }
}