問題描述
如何將日歷日期轉換為yyyy-MM-dd
格式.
How to convert calendar date to yyyy-MM-dd
format.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(date);
Date inActiveDate = null;
try {
inActiveDate = format1.parse(date1);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
這將產生 inActiveDate = Wed Sep 26 00:00:00 IST 2012
.但我需要的是2012-09-26
.我的目的是使用 Hibernate 標準將此日期與我的數據庫中的另一個日期進行比較.所以我需要 yyyy-MM-dd
格式的日期對象.
This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012
. But what I need is 2012-09-26
. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd
format.
推薦答案
Java Date
是自 1970 年 1 月 1 日 00:00:00 GMT 以來的毫秒數的容器.
A Java Date
is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.
p>
當你使用 System.out.println(date)
之類的東西時,Java 使用 Date.toString()
來打印內容.
When you use something like System.out.println(date)
, Java uses Date.toString()
to print the contents.
更改它的唯一方法是覆蓋 Date
并提供您自己的 Date.toString()
實現.現在在你啟動你的 IDE 并嘗試這個之前,我不會;它只會使事情復雜化.您最好將日期格式化為您想要使用(或顯示)的格式.
The only way to change it is to override Date
and provide your own implementation of Date.toString()
. Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).
LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"
String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12
Java 8 之前的版本
您應該使用 ThreeTen Backport
出于歷史目的保留以下內容(作為原始答案)
The following is maintained for historical purposes (as the original answer)
你可以做的是格式化日期.
What you can do, is format the date.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"
System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"
這些實際上是相同的日期,表示方式不同.
These are actually the same date, represented differently.
這篇關于java中的日歷日期為yyyy-MM-dd格式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!