好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

浅谈String类型如何转换为time类型存进数据库

String转换为time存进数据库

很久没试过将String类型转换并存进数据库中的date类型的字段,今天刚好遇到并解决了这个小问题,故写下来加深印象。

平时我们一般将数据库里面关于时间的处理字段设置为char之类的字符型,这样的好处是便于读取和存入,省掉了转换类型的麻烦。

但有时也会需要将字段设置为date类型用于存放时间等。

这里就列举一个例子

我的这个字段名是chusheng_time,也就是出生日期,类型设置为date类型。

java里面的类型是string类型

如下图:

我用的是java提供的传统的jdbc接口连接数据库

具体代码为:

?

1

2

3

4

5

6

7

8

9

10

PreparedStatement statement = database.connection.prepareStatement(sql);

try {

     SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" ); //设置日期格式

     java.util.Date d = sdf.parse(chushengTime);                //注意这里转换的是java.util.Date mysql,数据库也提供了一个自身的date模式,千万不能混淆

     statement.setDate( 4 , new java.sql.Date(d.getTime()));    //这里是将until.date的时间转换为 sql.date类型,这一步是必须的

} catch (ParseException e) {

     // TODO Auto-generated catch block

     e.printStackTrace();

     System.out.println( "出错" );

}

总的来说就是在java后台中将string类型的时间先转换为java.util.Date类型的时间,在插入数据库的时候强制转换为java.sql.Date类型,这样就能正常插入到数据库当中

String类型的数字转换为时间日期格式

问题描述

String类型的数字格式转换为时间日期格式,例如String time1=[1585107267188],将其转换为2020-03-25 11:34:27

直接上代码了:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

package com.jwdntjfx.Test;

import java.text.SimpleDateFormat;

import java.util.Date;

/**

  * 得到了一窜数字 例如: String time1="1585107267188";

  * 转换为日期格式

  */

public class test {

     public static void main(String[] args) {

         /**定义想要输出的日期格式**/

         SimpleDateFormat sdf1= new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );

         SimpleDateFormat sdf2= new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );

         SimpleDateFormat sdf3= new SimpleDateFormat( "yyyy年MM月dd日 HH时mm分ss秒" );

         /** 获取系统时间,是long类型**/

         long time= new Date().getTime();

         /**如果你的到是String类型,需要转换一下**/

         String time1= "1585107267188" ;

         long time2=Long.parseLong(time1);

         String time3=sdf1.format(time2);

         String time4=sdf2.format(time2);

         String time5=sdf3.format(time2);

         System.out.println(time3);  //输出结果是2020-03-25 11:34:27

         System.out.println(time4);  //输出结果是2020/03/25 11:34:27

         System.out.println(time5);  //输出结果是2020年03月25日 11时34分27秒

     }

}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/mjm_1251162714/article/details/80144231

查看更多关于浅谈String类型如何转换为time类型存进数据库的详细内容...

  阅读:30次