簡體   English   中英

格式化日期從mm / dd / yyyy到MM DD,YYYY

[英]Formatting date from mm/dd/yyyy to MM DD, YYYY

例如,它將格式化日期為2014年2月15日至2014年2月15日

我已經嘗試了一個轉換來獲得月份,但這是有效的,但我無法弄清楚如何完成剩下的工作。

這是我到目前為止:

private void formatDate()
{
    String month = dateDeparture.substring(0, dateDeparture.indexOf('/'));
    switch(dateDeparture)
    {
    case 1:
        month = "January";
        break;
    case 2:
        month = "February";
        break;
    case 3:
        month = "March";
        break;
    case 4:
        month = "April";
        break;
    case 5:
        month = "May";
        break;
    case 6:
        month = "June";
        break;
    case 7:
        month = "July";
        break;
    case 8:
        month = "August";
        break;
    case 9:
        month = "September";
        break;
    case 10:
        month = "October";
        break;
    case 11:
        month = "November";
        break;
    default:
        month = "December";
        break;  
    }
    dateDeparture = month+" "+dateDeparture.substring(dateDeparture.indexOf('/'),  dateDeparture.lastIndexOf('/'))+ dateDeparture.substring(dateDeparture.lastIndexOf('/'));

}

Java有一個名為SimpleDateFormat的類。 用它來實現你正在做的事情。

最好的方法是使用像SimpleDateFormat這樣的日期格式化類:

SimpleDateFormat numericDateFormatter = new SimpleDateFormat("MM/dd/yyyy");
Date date = numericDateFormatter.parse(dateDeparture);
SimpleDateFormat mixedDateFormatter = new SimpleDateFormat("MMMMMMMMM d, yyyy");
String dateNew = mixedDateFormatter.format(date);

只要您使用Java 7,就可以在switch語句中使用String ...

但是,您當前的代碼存在兩個問題......

一,你使用的是dateDeparture而不是month

switch(dateDeparture)

而你的case語句使用的是int而不是String

case 1:

相反,你需要使用更像......

switch (month) {
    case "1":
    case "01":
        month = "January";
        break;
}

現在,因為你的月份“可能”被歸零,你需要考慮兩種情況......

如果您使用的是Java 6或eailer,則需要將String值轉換為int ...

int monthValue = Integer.parseInt(month);
switch (monthValue) {
    case 1:
        //...

一種更簡單的方法是使用可用的內置API ...

首先將String值轉換為Date值...

SimpleDateFormat in = new SimpleDateFormat("MM/dd/yyyy");
Date date = in.parse(dateDeparture);

然后格式化日期......

SimpleDateFormat out = new SimpleDateFormat("MMMM dd, yyyy");
String value = out.format(date);

仔細查看SimpleDateFormat以獲取更多詳細信息......

做這個...

//splits string based on / delimiter 
String[] MDY = dateDeparture.split("/");
int month = Integer.parseInt(MDY[0]);
int day = Integer.parseInt(MDY[1]);
int year = Integer.parseInt(MDY[2]);

然后根據自己的喜好在月份上使用switch語句並格式化日期年份

暫無
暫無

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

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