SimpleDateFormat的使用:SimpleDateFormat对日期Date类的格式化和解析

SimpleDateFormat的两个操作:
1、格式化:日期 ----->字符串
2、解析:格式化的逆过程,字符串 -----> 日期

public class DateTimeTest {
    
     
@Test
public void testSimpleDateFormat() throws ParseException {
    
    
//实例化SimpleDateFormat:使用默认的构造器
    SimpleDateFormat sdf = new SimpleDateFormat();
    //格式化:日期 ----->字符串
    Date date = new Date();
    System.out.println(date);
    String format = sdf.format(date);
    System.out.println(format);
//解析:格式化的逆过程,字符串 -----> 日期
    String str = "19-12-18 上午11:43";
    Date date1 = sdf.parse(str);
    System.out.println(date1);
    
//-----按照指定的方式格式化和解析:调用带参的构造器-----

//日期格式:年、月、日、公元、时、分、秒
// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MMMM.dd GGG hh:mm aaa"); 

//日期格式:年、月、日、上午(下午)、时、分、秒
// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MMMM.dd a hh:mm aaa"); 

//日期格式:年、月、日、时、分、秒
	SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
//格式化 
	String format1 = sdf1.format(date); 
	System.out.println(format1);//2020-09-24 09:42:37 
//解析:要求字符串必须符合SimpleDateFormat识别的格式(通过构造器参数体现), 
//否则,抛出异常 
	Date date2 = sdf1.parse("2020-09-24 09:42:37"); 
	System.out.println(date2); 
}

执行结果如下所示:

执行效果如图所示

猜你喜欢

转载自blog.csdn.net/m0_50963943/article/details/108783941