Date 类的 API不易于国际化,大部分被废弃了,java.text.SimpleDateFormat类 是一个不与语言环境有关的方式来格式化和解析日期的具体类。
它允许进行格式化: 日期 → 文本; 解析: 文本 → 日期

package com.klvchen.java;

import org.junit.Test;

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

public class DateTimeTest {
    /*
    simpleDateFormat的使用: SimpleDateFormat对日期Date类的格式化和解析
    两个操作:
        格式化: 日期 ---> 字符串
        解析: 格式化的逆过程,字符串 ---> 日期

     */
    @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 = "21-9-2 下午8:02";
        Date date1 = sdf.parse(str);
        System.out.println(date1);

        //**************按照指定的方式格式化和解析: 调用带参的构造器***************
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //格式化
        String format1 = sdf1.format(date);
        System.out.println(format1);
        //解析
        //解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现),
        //否则,抛异常
        Date date2 = sdf1.parse("2021-09-02 20:06:50");
        System.out.println(date2);
    }

    // 将字符串"2020-09-08" 转换为 java.sql.Date

    @Test
    public void testExer() throws ParseException{
        String birth = "2020-09-08";

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf1.parse(birth);
        System.out.println(date);

        java.sql.Date birthDate = new java.sql.Date(date.getTime());
        System.out.println(birthDate);
    }
}

相关文章:

  • 2022-12-23
  • 2022-02-19
  • 2021-07-28
  • 2022-12-23
  • 2021-10-08
  • 2022-12-23
  • 2021-10-28
  • 2021-12-30
猜你喜欢
  • 2021-10-02
  • 2021-11-13
  • 2022-01-29
  • 2022-12-23
  • 2021-12-05
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案