Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

Java 8 - SQL Timestamp to Instant with properly formatted time

I've read through the available q and a on SO, but nothing I have found answers my question of how to format my time in 12hour format.

Following is my code that runs a query on a MySQL database and returns results, checking to see if an appointment is within 15 minutes of login so an alert can pop.

public void apptCheck(int userId) throws SQLException {
        
        // this method checks for an appointment occurring within 15 minutes of login
        
        Statement apptStatement = DBQuery.getStatement();
        String apptQuery = "Select apt.start, cs.customerName from DBName.appointment apt "
                + "JOIN DBName.customer cs ON cs.customerId = apt.customerId WHERE "
                + "userId = " + userId + " AND start >= NOW() AND start < NOW() + interval 16 minute";
        apptStatement.execute(apptQuery);
        ResultSet apptRs = apptStatement.getResultSet();
        while(apptRs.next()) {
            Timestamp apptTime = apptRs.getTimestamp("start");
            
            
            ResourceBundle languageRB = ResourceBundle.getBundle("wgucms/RB", Locale.getDefault());
            Alert apptCheck = new Alert(AlertType.INFORMATION);
            apptCheck.setHeaderText(null);
            apptCheck.setContentText(languageRB.getString("apptSoon") + " " + apptTime.toInstant().atZone(ZoneId.systemDefault()));
           
            apptCheck.showAndWait();
           
           
        } 

My result is:

enter image description here

I want the time to display 3:00, not the 19:00 - 06:00. How can I make that happen?

question from:https://stackoverflow.com/questions/65874732/java-8-sql-timestamp-to-instant-with-properly-formatted-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
 ZonedDateTime zonedDateTime=ZonedDateTime.of(apptTime.toLocalDateTime(),ZoneId.systemDefault());

You can use ZonedDateTime and format the time as you want.

docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html ZonedDateTime has a lot of features you can see all here and you can get the hour, minute, day etc.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss"); 
String formattedString = zonedDateTime.format(formatter); 

if you only want time in 12hour format you can use this


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...