常见日期转换

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.junit.Test;

public class TestDate {

 /**
  * Date类型转换为String类型,例如:2018-11-04 13:52:23
  */
 public void getNowDateToStr() {
  Date currentTime = new Date();
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  String dateString = formatter.format(currentTime);
 }

 /**
  * Date类型转换为String类型,例如:2018-11-04
  */
 public void date() {
  Date currentTime = new Date();
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  String dateString = formatter.format(currentTime);
 }

 /**
  * Date类型转换为String类型,例如:2018-11-04
  */
 public void date1() {
  SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
  Date currentTime = new Date();
  String dateString = formatter.format(currentTime);
 }

 /**
  * String类型转换为Date类型,例如:2018-11-04 13:52:23
  */
 public void date2() {
  String dateString = "2018-11-04 13:52:23";
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  ParsePosition pos = new ParsePosition(0);
  Date strtodate = formatter.parse(dateString, pos);
 }

 /**
  * String类型转换为Date类型,例如:2018-11-04
  */
 public void date3() {
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  Date d = new Date();
  String dateStr = formatter.format(d);
 }

 /**
  * String类型转换为Date类型,例如:2018-11-04
  */
 public void date4() {
  String dateString = "2018-11-04";
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  ParsePosition pos = new ParsePosition(0);
  Date strtodate = formatter.parse(dateString, pos);
 }

 /**
  * Date类型转换为String类型,例如:20181104 135223
  */
 public void getNowDate5() throws ParseException {
  Date currentTime = new Date();
  SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
  String dateString = formatter.format(currentTime);
 }

}

你可能感兴趣的:(常见日期转换)