简体   繁体   English

如何在时间戳中更改日期格式

[英]How to change date format in timestamp

I'm using preparedStatement to update my sql table. 我正在使用prepareStatement更新我的sql表。 Currently my date format is yyyy-mm-dd how to make it dd-mm-yyyy. 目前我的日期格式是yyyy-mm-dd,如何使其成为dd-mm-yyyy。

    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306?user=root&password=1234&useSSL=false");
        con.setAutoCommit(false);
        pstmt = con.prepareStatement(qry);
        sp = con.setSavepoint();
        System.out.println("Enter your name");
        String name = sc.next();
        System.out.println("Enter your contact number");
        long phoneNum = sc.nextLong();
        System.out.println("Purpose of visit");
        String purpose = sc.next();

        pstmt.setString(1, name);
        pstmt.setLong(2, phoneNum);
        pstmt.setString(3, purpose);

         java.sql.Timestamp  dd = new java.sql.Timestamp(new java.util.Date().getTime());
        pstmt.setTimestamp(4, dd);
        pstmt.setTimestamp(5, dd);
        pstmt.executeUpdate();
        con.commit();

The terrible java.sql.Timestamp class is now legacy, no longer needed as of JDBC 4.2 and later. 可怕的java.sql.Timestamp类现在是旧类,从JDBC 4.2及更高版本开始不再需要。 For database work, use OffsetDateTime instead, possibly adjusting to/from Instant or ZonedDateTime . 对于数据库工作,请改用OffsetDateTime ,可能在InstantZonedDateTime调整。

LocalDate

You seem to want only the date, without a time-of-day and without a time zone or offset-from-UTC. 您似乎只想要日期,没有时间,没有时区或UTC偏移量。

To represent the date-only, use LocalDate class. 要表示仅日期,请使用LocalDate类。

LocalDate ld = LocalDate.parse( "2019-01-23" ) ;  // By default, parses strings in standard ISO 8601 format: YYYY-MM-DD. 

To capture the current date, specific a time zone. 要捕获当前日期,请指定一个时区。

ZoneId z = ZoneId.systemDefault() ;
LocalDate ld = LocalDate.now( z ) ;

To generate text representing that value, use DateTimeFormatter . 要生成表示该值的文本,请使用DateTimeFormatter

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
String output = ld.format( f ) ;

JDBC JDBC

To write a LocalDate object to the database in a column of a data type akin to the standard-SQL type DATE : 要在类似于标准SQL类型DATE的数据类型的列中将LocalDate对象写入数据库:

myPreparedStatement.setObject( … , ld ) ;

Retrieve from database: 从数据库检索:

LocalDate ld = myResultSet( … , LocalDate.class ) ;

You can simply write below code to change the format as required. 您只需编写以下代码即可根据需要更改格式。

java.sql.Timestamp dd = new java.sql.Timestamp(new java.util.Date().getTime());
String date = new java.text.SimpleDateFormat("dd-MM-yyyy").format(dd);
System.out.println(date);

Output : 27-06-2019 输出:27-06-2019

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM