[英]How to change date and time format from“yyyy-MM-dd HH:mm:ss” to “h:mm a”?
我正在使用下面的代碼將數據和時間格式化為時間,但是任何人都不能幫助我解決此問題,這是行不通的。
try {
String actualDate = m.getDate();//get date as"28-aug-2015 6:46:32 pm"
Date Date= new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss").parse(actualDate);
convertDate = new SimpleDateFormat("h:mm a").format(Date);//6:46 am
}
catch (ParseException e) {
e.printStackTrace();
}
轉換格式后,我的“ convertDate”值為“ 6.46 am”,但現在的時間是“ 6:46 pm”,我該如何解決此問題。
您那里有一些錯誤,這就是您想要的:
Date date= new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss").parse(actualDate);
convertDate = new SimpleDateFormat("H:mm").format(date);
如果您使用上午/下午,則:
Date date= new SimpleDateFormat("dd-MMM-yyyy h:mm:ss a").parse(actualDate);
convertDate = new SimpleDateFormat("h:mm a").format(date);
現代方法使用java.time類。
對於您的月份名稱和AM / PM的拼寫,我們忽略了美國英語的文化規范,我們使用構建器將格式器標記為不區分大小寫。
String input = "28-aug-2015 6:46:32 pm";
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
builder.parseCaseInsensitive();
builder.appendPattern( "dd-MMM-uuuu h:m:s a" );
DateTimeFormatter formatter = builder.toFormatter().withLocale( Locale.US) ;
LocalDateTime ldt = LocalDateTime.parse( input , formatter );
看到此代碼在IdeOne.com上實時運行 。
輸入:28-aug-2015 6:46:32 pm
ldt.toString():2015-08-28T18:46:32
如果您的輸入符合某些特定語言環境的文化規范,請使用DateTimeFormatter.ofLocalizedDateTime
代替此構建器方法。
java.time框架內置於Java 8及更高版本中。 這些類取代了麻煩的舊的舊式日期時間類,例如java.util.Date
, Calendar
和SimpleDateFormat
。
要了解更多信息,請參見Oracle教程 。 並在Stack Overflow中搜索許多示例和說明。 規格為JSR 310 。
現在處於維護模式的Joda-Time項目建議遷移到java.time類。
您可以直接與數據庫交換java.time對象。 使用與JDBC 4.2或更高版本兼容的JDBC驅動程序 。 不需要字符串,不需要java.sql.*
類。
在哪里獲取java.time類?
ThreeTen-Extra項目使用其他類擴展了java.time。 該項目為將來可能在java.time中添加內容提供了一個試驗場。 您可以在這里找到一些有用的類,比如Interval
, YearWeek
, YearQuarter
,和更多 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.