2011-03-07 62 views
0
 SimpleDateFormat sdf = new SimpleDateFormat("ddMMM", Locale.ENGLISH); 

     try { 

     sdf.parse(sDate); 
     } catch (ParseException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     } 

我的日期格式是04AUG2011,我想要20110804.所以我該怎麼做?在java中的日期格式

+1

[從8月14日格式日至年月日]的可能重複(http://stackoverflow.com/questions/5220061/format-date-from-14-aug-to-yyyymmdd) – 2011-03-07 14:43:47

+3

你問這**確切**問題之前。 – 2011-03-07 14:44:23

+0

是的,但我試過,我有一個新的錯誤... – 2011-03-07 14:48:00

回答

2

使用以下格式:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH); 

我想你需要分析和輸出之間的區別:

SimpleDateFormat parseFormat = new SimpleDateFormat("MMMdd", Locale.ENGLISH); 
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH); 
String dateStr = "06Sep"; 
// parse with 06Sep format 
Date din = parseFormat.parse(dateStr); 
// output with 20101106 format 
System.out.println(String.format("Output: %s", outputFormat.format(din))); 
+0

但我得到了這個錯誤..解析日期:「06Sep」 – 2011-03-07 14:44:16

+0

@Praneel,這不是你發佈的例子。閱讀其他格式的javadocs! – 2011-03-07 14:50:35

+0

您需要區分解析和輸出。如果您的日期爲ni「06Sep」格式,則需要新的'SimpleDateFormat(「ddMMM」)' – 2011-03-07 14:51:08

0

更改日期格式,以

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH); 
+1

-1:將不起作用,因爲「mm」將輸出分鐘而非月份值。 – 2011-03-07 14:41:57

+0

對不起,我以爲我按了shift鍵,現在編輯了。 – Manoj 2011-03-07 14:43:10

0

這裏是一個完整的工作示例。我希望下次你會做你自己的工作。

/** 
* 
*/ 

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


/** 
* @author The Elite Gentleman 
* 
*/ 
public class Test { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     try { 
      String date = "06Sep2011"; 
      SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyyyy", Locale.ENGLISH); 
      Date d = sdf.parse(date); 

      SimpleDateFormat nsdf = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH); 
      String nd = nsdf.format(d); 
      System.out.println(nd); 
     } catch (ParseException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

}