Set date and time in java.sql.Timestamp

为君一笑 提交于 2020-12-27 06:49:07

问题


Please tell me how to set the date (current date minus one day) and time equal to 19:00:00 using such a construction?

new java.sql.Timestamp(java.util.Calendar.getInstance.getTime().getTime())

LocalDateTime don't use.


回答1:


I recommend you do it using the java.time (the modern date-time API).

Solution, purely using the modern API:

import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        OffsetDateTime odt = ZonedDateTime.now(ZoneId.systemDefault())
                                .minusDays(1)
                                .with(LocalTime.of(19, 0))
                                .toOffsetDateTime();

        System.out.println(odt);
    }
}

Output:

2020-12-24T19:00Z

You can use the OffsetDateTime in your JDBC code as follows:

PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, odt);
st.executeUpdate();
st.close();

However, if you still want to use java.sql.Timestamp, you can use ZonedDateTime with the applicable timezone to get the required date-time and then convert it into Instant from which you can get Epoch milliseconds. You can Finally use the Epoch milliseconds to construct an instance of java.sql.Timestamp.

import java.sql.Timestamp;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime zdt = ZonedDateTime.now(ZoneId.systemDefault())
                            .minusDays(1)
                            .with(LocalTime.of(19, 0));
        
        Timestamp timestamp = new Timestamp(zdt.toInstant().toEpochMilli());
        System.out.println(timestamp);
    }
}

Output:

2020-12-24 19:00:00.0

Notes:

  1. I have used ZoneId.systemDefault() which uses the JVM's timezone. Change it to applicable timezone e.g. ZoneId.of("Europe/London").
  2. Instant belongs to the modern date-time API. Learn about the modern date-time API from Trail: Date Time.
  3. For whatsoever reason if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Solution, purely using the legacy API:

import java.sql.Timestamp;
import java.util.Calendar;

public class Main {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 19);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());
        System.out.println(timestamp);
    }
}

Output:

2020-12-24 19:00:00.0



回答2:


This is my code

Set date to yesterday with Calendar.add(Calendar.DAY_OF_YEAR, -1)

Compare hour with Calendar.get(Calendar.HOUR_OF_DAY)

getHour of java.sql.Timestamp is Deprecated.

replaced by Calendar.get(Calendar.HOUR_OF_DAY).

import java.sql.Timestamp;
import java.util.Calendar;

Calendar calendar = Calendar.getInstance(); // 2020-12-25 19:42:57.739
calendar.add(Calendar.DAY_OF_YEAR, -1);
Timestamp timestamp = new Timestamp(calendar.getTimeInMillis());

System.out.println(timestamp); // 2020-12-24 19:42:57.739
System.out.println(19 == calendar.get(Calendar.HOUR_OF_DAY)); // true

Bye!




回答3:


// import java.util.Calendar;
// import java.sql.Timestamp;
Calendar cal = Calendar.getInstance(Locale.ENGLISH); // Get current date and time.
cal.add(Calendar.DAY_OF_MONTH, -1);                  // Subtract one day from the value
cal.set(Calendar.HOUR_OF_DAY, 19);                   // Set the hour to 19
cal.set(Calendar.MINUTE, 0);                         // Set the minute to 0 (zero)
cal.set(Calendar.SECOND, 0);                         // Set the seconds to 0
Timestamp ts = new Timestamp(cal.getTimeInMillis());

Note that the Locale.ENGLISH is not required. It just sets the names, like day and month, to English when you print the value of cal.



来源:https://stackoverflow.com/questions/65447278/set-date-and-time-in-java-sql-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!