[英]How to display only time part from date time combination in java
我是Java新手。 我在數據庫中從數據庫中檢索我的第一列,表示數據為:
2014-09-01 10:00:00.000
現在我想只顯示時間:
10:00:00
怎么做? 我檢索我的列的代碼是:
public String[] getChartTime() throws SQLException { List < String > timeStr = new ArrayList < String > (); String atime[] = null; getConnection(); try { con = getConnection(); String sql = "exec vcs_gauge @gauge_name=?,@first_rec_time=?,@last_rec_time=?"; DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("date is " + df.format(currentDate)); clstmt = con.prepareCall(sql); clstmt.setString(1, "vs3_bag"); clstmt.setString(2, "2014-09-01 10:00:00"); clstmt.setString(3, "2014-09-01 11:00:00"); clstmt.execute(); rs = clstmt.getResultSet(); while (rs.next()) { // Just get the value of the column, and add it to the list timeStr.add(rs.getString(1)); } } catch (Exception e) { System.out.println("\\nException in Bean in getDbTable(String code):" + e); } finally { closeConnection(); } // I would return the list here, but let's convert it to an array atime = timeStr.toArray(new String[timeStr.size()]); for (String s: atime) { System.out.println(s); } return atime; }
使用SimpleDateFormat
:
java.util.Date date = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(date));
如果您將日期作為String,則可以在之前的步驟中將其解析為java.util.Date:
SimpleDateFormat sdf = new SimpleDateFormat("YOUR_DATE_PATTERN");
Date date = sdf.parse(string);
根據https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html使用模式
如果我已正確理解問題2014-09-01 10:00:00.000
在字符串中,並且必須從中提取10:00:00
。 以下是我的解決方案。
.
作為分界符並從中獲取第一個刺痛。 以上的事情都是用線完成的。
str.split("\\s")[1].split("\\.")[0];
String str = new String("2014-09-01 10:00:00.000");
String time = str.split("\\s")[1].split("\\.")[0];
System.out.print(time);
10:00:00
有關詳細信息,請查看以下鏈接:
請參閱此處的官方Java文檔
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDate {
public static void main(String[] args){
DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss a");
Date date = new Date();
String time=dateFormat.format(date);
System.out.println(time);
}
}
我明白了,只需使用substring()作為
while(rs.next()) {
// Just get the value of the column, and add it to the list
timeStr.add(rs.getString(1).substring(11,16));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.