[英]Date formatter is not formatting the date correctly
我用以下java代碼編寫了這個格式來格式化特定格式的日期和時間。 您可以在ideone上看到以下代碼。
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
class timeAndDateTransformation{
public static void main(String[] argv){
Calendar newDate = new GregorianCalendar(2009,7,1,15,20,00);
SimpleDateFormat dateFormant = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat timeFormant = new SimpleDateFormat("HH:mm:ss");
System.out.println(dateFormant.format(newDate.getTime()).toString());
System.out.println(timeFormant.format(newDate.getTime()).toString());
}
}
它給了我以下輸出:
2009/08/01
15:20:00
在這個輸出中休息一切都完全沒問題,除了月份。 我作為一個月通過7但是在這個for-matter輸出中它給出8作為輸出。 請指出我在哪里做錯了。 我對java的日期/日歷類不是很熟悉,所以請耐心等待。
月份是0,你通過7,所以解析到8月。
來自java.util.Date的api文檔:
一個月由0到11的整數表示; 0是1月,1是2月,依此類推; 因此11月是12月。
將月份從零開始實際上是違反直覺的。 我想我們在某些時候都被那個人燒了。
Java中的month字段基於零。 GregorianCalendar.JANUARY是0 ...等等。因此,如果要將日期傳入構造函數,請在月份值中添加一個。
如果你看一下[JavaDoc here] [1],它就會為你解釋。
[1]: http : //download.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html#set (int,int,int)
人類喜歡看第一個月(1月)是1,這就是SimpleDateFormat
作用。
然而,計算機喜歡看從0開始的事情,這就是GregorianCalendar
管理month
參數的方式。 請參閱GregorianCalendar的構造函數和month
參數的說明。
[Java考慮1月份0月。] [1]但是當您使用SimpleDateFormat輸出月份數時,它使用標准的1月是1月系統。 因此第7個月輸出為8。
如果您在使用Joda Time時遇到JDK日期和日歷的問題,那就容易多了
[1]: http : //download.oracle.com/javase/1.4.2/docs/api/java/util/GregorianCalendar.html#GregorianCalendar (int,int,int)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.