常見日期轉換
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); }
}