簡體   English   中英

Java simpledateformat月返回零

[英]Java simpledateformat returns zero for month

這可能是重復的,但是我無法弄清楚為什么當將MMM指定為MMM並與mm(numeric)一起使用時,該月返回為零。 這里的任何幫助將不勝感激?

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Locale;

 public class time1 {

 public static void main(String[] args) {

    DateFormat originalFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
    DateFormat targetFormat = new SimpleDateFormat("yyyy-mm-dd");
    Date date = null;
    try {
            date = originalFormat.parse("26-Aug-2011");
    } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }
    String formattedDate = targetFormat.format(date);
    System.out.println("old date: " + date);
    System.out.println("new date: " + formattedDate);
 }
}

輸出為:

舊日期:IST 2011年8月26日00:00:00
新日期:2011-00-26

當格式更改為dd-mm-yyyy且日期為26-08-2011時,輸出為

舊日期:IST 2011年1月26日星期三00:07:00
新日期:2011-07-26

我無法理解MMM失敗的原因,我所有的日期都采用格式(2011年8月26日),因此我需要將其轉換為yyyy-mm-dd(26-07-2011)。

文檔中 ,我可以說

DateFormat targetFormat = new SimpleDateFormat("yyyy-mm-dd");

需要更改為

DateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
// this gives you the Date in Digits.

根據文檔,

“ M”用於年份中的月份,而
“ m”表示小時。

因此,您的“ mm”返回的分鍾數默認為00:00,這就是您獲得的輸出。 這將為您提供以下輸出。

old date: Fri Aug 26 00:00:00 IST 2011
new date: 2011-08-26

java.time

您正在使用麻煩的舊日期時間類,這些類現在已被遺留,由java.time類取代。

String input = "26-Aug-2011" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f ) ;

您想要的YYYY-MM-DD輸出格式恰好符​​合ISO 8601標准。 解析/生成字符串時,java.time類默認使用標准格式。

String output = ld.toString() ;

2011-08-26

看到此代碼在IdeOne.com上實時運行


關於java.time

java.time框架內置於Java 8及更高版本中。 這些類取代了麻煩的舊的舊式日期時間類,例如java.util.DateCalendarSimpleDateFormat

現在處於維護模式Joda-Time項目建議遷移到java.time類。

要了解更多信息,請參見Oracle教程 並在Stack Overflow中搜索許多示例和說明。 規格為JSR 310

在哪里獲取java.time類?

ThreeTen-Extra項目使用其他類擴展了java.time。 該項目為將來可能在java.time中添加內容提供了一個試驗場。 您可以在這里找到一些有用的類,比如IntervalYearWeekYearQuarter ,和更多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM