史上最全java日期转换

史上最全java日期转换

使用jodaTime,满足各种转化姿势

依赖

引入jodaTime依赖

<dependency>
    <groupId>joda-timegroupId>
    <artifactId>joda-timeartifactId>
    <version>2.9.9version>
dependency>

Mysql日期和时间

mysql类型 对应java类型 日期或时间格式 日期或时间范围 默认值 占用空间
YEAR java.sql.Date YYYY 1901 ~ 2155 0000 1 bytes
TIME java.sql.Time HH:MM:SS -838:59:59 ~ 838:59:59 00:00:00 3 bytes
DATE java.sql.Date YYYY-MM-DD 1000-01-01 ~ 9999-12-3 0000-00-00 4 bytes
TIMESTAMP java.sql.Timestamp YYYY-MM-DD HH:MM:SS 1970-01-01 00:00:01 UTC ~ 2038-01-19 03:14:07 UTC 00000000000000 4 bytes
DATETIME java.sql.Timestamp YYYY-MM-DD HH:MM:SS 1000-01-01 00:00:00 ~ 9999-12-31 23:59:59 0000-00-00 00:00:00 8 bytes

列举这个表格,是为了快速查找对应类型,方便我们建立java语言与SQL语言的连接通道。

转换

时间类型转化的场景很多,下面我举几个例子,基本解决了大多数场景,希望大家能举一反三

  1. yyyy-MM-dd 转 java.sql.Date
String fmtPattern = "yyyy-MM-dd";
DateTimeFormatter fmt = DateTimeFormat.forPattern(fmtPattern);
DateTime dateTime = fmt.parseDateTime("2020-08-10");
java.sql.Date date = new java.sql.Date(dateTime.getMillis());
System.out.println(date.toString()); // 2020-08-10
  1. YYYY-MM-DD HH:MM:SS 转 java.util.Date

    String fmtPattern = "yyyy-MM-dd HH:mm:ss";
    DateTimeFormatter fmt = DateTimeFormat.forPattern(fmtPattern);
    DateTime dateTime = fmt.parseDateTime("2020-08-10 10:30:20");
    java.util.Date date = new java.util.Date(dateTime.getMillis());
    System.out.println(date.toString()); // Mon Aug 10 10:30:20 CST 2020
    
  2. YYYY-MM-DD HH:MM:SS 转 java.util.Timestamp

String fmtPattern = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter fmt = DateTimeFormat.forPattern(fmtPattern);
DateTime dateTime = fmt.parseDateTime("2020-08-10 10:30:20");
java.sql.Timestamp timestamp = new Timestamp(dateTime.getMillis());
System.out.println(timestamp.toString()); // 2020-08-10 10:30:20.0
System.out.println(timestamp.getTime()); // 1597026620000
  1. HH:MM:SS 转 java.sql.Time

    String fmtInput = "HH:mm:ss";
    DateTimeFormatter fmt = DateTimeFormat.forPattern(fmtInput);
    DateTime dateTime = fmt.parseDateTime("11:30:20");
    Time time = new Time(dateTime.toDate().getTime());
    System.out.println(time.toString()); // 11:30:20
    
  2. YYYY 转 java.sql.Date

    String fmtPattern = "yyyy";
    DateTimeFormatter fmt = DateTimeFormat.forPattern(fmtPattern);
    DateTime dateTime = fmt.parseDateTime("2020");
    java.sql.Date date = new Date(dateTime.getMillis());
    System.out.println(date.toString()); // 2020-01-01
    

你可能感兴趣的:(工具类,java,sql,mysql)