String和Date相互转换

/**
 *字符串yyyyMMddHHmmss转成 date  yyyy-MM-dd hh:mm:ss
 */
public static Date stringToDate1() throws ParseException {
    String str="20180516143338";
    DateFormat format= new SimpleDateFormat("yyyyMMddHHmmss");
    Date date=format.parse(str);
    System.out.print(date);
    return date;
}
/**
 *字符串yyyyMMddHHmmss转成 date  yyyy-MM-dd
 */
public static Date stringToDate2() throws ParseException {
    String str="20180516143338";
    DateFormat format= new SimpleDateFormat("yyyyMMddHHmmss");
    Date date=format.parse(str);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String dateString = formatter.format(date);
    Date newDate = formatter.parse(dateString);
    System.out.print(newDate);
    return newDate;
}

/**
 *当前时间 转成 String  "yyyy-MM-dd HH:mm:ss"
 */
public static String nowToDate1() throws ParseException {
    Date date=new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String result=formatter.format(date);
    Date resultDate = formatter.parse(result);
    System.out.print(resultDate);
    return result;
}
/**
 *获取当前小时数
 */
public static String getHour() {
       Date currentTime = new Date();
       SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       String dateString = formatter.format(currentTime);
       String hour;
       hour = dateString.substring(11, 13);
        System.out.print(hour);
       return hour;
      }

/**
 *获取当前分钟数
 */
public static String getMin() {
       Date currentTime = new Date();
       SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       String dateString = formatter.format(currentTime);
       String min;
       min = dateString.substring(14, 16);
        System.out.print(min);
       return min;
      }




public static void main(String[] args) throws Exception {
    getHour();
}

你可能感兴趣的:(String和Date相互转换)