2017-05-31 74 views

回答

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

public class Main { 

    public static void main(String[] args) throws ParseException { 

    String theInDate = "2/20/2016"; 

    String theInFormat = "MM/dd/yyyy"; 
    String theOutFormat = "MMM dd, yyyy"; 

    final SimpleDateFormat theSdfInputFormatter = new SimpleDateFormat(theInFormat); 
    final SimpleDateFormat theSdfOutputFormatter = new SimpleDateFormat(theOutFormat); 

    final Date theDate = theSdfInputFormatter.parse(theInDate); 

    final String theDateText = theSdfOutputFormatter.format(theDate); 

    System.out.println(theDateText); 

    } 
} 

您可能還想檢查日期解析器中的setLinient(true)功能。

,並用新的日期API

String theInDate = "2/20/2016"; 

    String theInFormat = "M/d/yyyy"; 
    String theOutFormat = "MMM dd, yyyy"; 

    final DateTimeFormatter theSdfInputFormatter = DateTimeFormatter.ofPattern(theInFormat); 
    final DateTimeFormatter theSdfOutputFormatter = DateTimeFormatter.ofPattern(theOutFormat); 

    final LocalDate theDate = LocalDate.from(theSdfInputFormatter.parse(theInDate)); 

    final String theDateText = theSdfOutputFormatter.format(theDate); 

    System.out.println(theDateText); 

注意線程安全的。看看javadoc。 此解決方案適用於Java。對於Android,標記爲,應該非常相似。 即使這是一個重複的答案,我希望它可以幫助某人快速解決問題,並理解它如何用於進一步自我學習。

+0

回答明顯的重複問題沒有幫助。 –

+0

僅供參考,麻煩的舊日期時間類如['java.util.Date'](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html),[ 'java.util.Calendar'](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html)和'java.text.SimpleTextFormat'現在是[legacy]( https://en.wikipedia.org/wiki/Legacy_system),由[java.time]代替(https://docs.oracle.com/javase/8/docs/api/java/time/package-summary。 html)類。請參見[Oracle教程](https://docs.oracle.com/javase/tutorial/datetime/TOC.html)。 –

相關問題