2013-06-26 34 views
-1

在我的代碼我收到日期字符串:將日期轉換爲java中的字符串?

date="2013-06-15" 

我希望它轉換爲2013年6月15日。我曾嘗試過dateFormat:

DateFormat df = new SimpleDateFormat("yyyy-mm-dd"); 
String date = df.format(det); 
DateFormat f2 = new SimpleDateFormat("dd-mmmm-yyyy"); 
date=f2.format(date).toLowerCase(); 
out.println("DATE"+date); 

但它給了空指針可能任何人都可以幫助我做到這一點。請幫忙?

+2

「字符串日期= df.format(DET);」什麼是det? – Bathsheba

+0

NPE在哪裏拋出? – Kai

回答

1

第一您的日期字符串轉換爲日期,然後將其轉換爲你需要的格式

package naveed.workingfiles; 

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

public class DateToString { 

public static void main(String[] args) { 

String laDate="2013-06-15"; 
String dateString = laDate.substring(8, 10) + "/" 
      + laDate.substring(5, 7) + "/" 
      + laDate.substring(0, 4); 
Date date= new SimpleDateFormat("dd/MM/yyyy").parse(dateString); 
String dateFormat = "dd-MMM-yyyy"; 
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, new Locale("en_US")); 
String tDate = sdf.format(date); 
System.out.println(tDate);//here your String date 

} 

} 
2
String dateString="2013-06-15"; 
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateString); 
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy"); 
DateFormat df2 = new SimpleDateFormat("dd MMM yyyy"); 
System.out.println(df.format(date).toLowerCase());//print 15-jun-2013 
System.out.println(df.format(date));//print 15-Jun-2013 
System.out.println(df2.format(date));//print 15 Jun 2013 
1
// Create an instance of SimpleDateFormat used for formatting 
// the string representation of date (month/day/year) 
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 

// Get the date today using Calendar object. 
Date today = Calendar.getInstance().getTime();   
// Using DateFormat format method we can create a string 
// representation of a date with the defined format. 
String reportDate = df.format(today); 

// Print what date is today! 
System.out.println("Report Date: " + reportDate); 
1

這是不是要去工作:format()不帶字符串參數:

String date = df.format(det); 
DateFormat f2 = new SimpleDateFormat("dd-mmmm-yyyy"); 
date=f2.format(date).toLowerCase(); 

試試這個:

String dateAsString = "2013-06-15" 
DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
Date date = df.parse(dateAsString); 
df = new SimpleDateFormat("dd MMM yyyy"); 
out.println("DATE"+df.format(date)); 
+1

這實際上是錯誤的,M =月,m =分鐘 – fareed

+0

@fareed thx。該死的複製粘貼錯誤;) –

+0

歡迎:) – fareed

1

這將工作

String dateStr = "2013-06-15"; 
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
    Date date=df.parse(dateStr); 
    DateFormat f2 = new SimpleDateFormat("dd-MMM-yyyy"); 
    System.out.println(f2.format(date));