java中的日期格式

时间:2011-04-29 06:01:26

标签: java

我想以不同格式转换日期。

例如,

String fromDate =“2011-04-22”; 我想将此转换为日期为“2011年4月22日”

我该怎么做?

先谢谢

5 个答案:

答案 0 :(得分:3)

你想要的是因为22日的“nd”而有点棘手。根据当天,它需要不同的后缀。 SimpleDateFormat不支持这样的格式。你必须写一些额外的代码才能得到它。这是一个例子,但它仅限于在某些地区工作,如美国:

SimpleDateFormat fromFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat toFormat = new SimpleDateFormat("d'__' MMM, yyyy");

String fromDate = "2011-04-22";
Date date = fromFormat.parse(fromDate);
String toDate = toFormat.format(date);

Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day = cal.get(Calendar.DAY_OF_MONTH);
if (day % 10 == 1 && day != 11) {
    toDate = toDate.replaceAll("__", "st");
} else if (day % 10 == 2 && day != 12) {
    toDate = toDate.replaceAll("__", "nd");
} else if (day % 10 == 3 && day != 13) {
    toDate = toDate.replaceAll("__", "rd");
} else {
    toDate = toDate.replaceAll("__", "th");
}

System.out.println(toDate);

答案 1 :(得分:1)

您可以使用SimpleDateFormat解析给定格式,然后使用不同的SimpleDateFormat

编写第二个表单
SimpleDateFormat from = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat to = new SimpleDateFormat("dd MMM, yyyy");

Date dat = from.parse("2011-04-22");
System.out.println(to.format(dat));

不知道如果有办法将'nd'添加到'22nd'。

答案 2 :(得分:1)

按照此代码删除日期序号。它运行成功。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class patrn {

    private static String deleteOrdinal(String dateString) {
        Pattern p1 = Pattern.compile("([0-9]+)(st|nd|rd|th)");
        Matcher m = p1.matcher(dateString);
        while (m.find()) {
            dateString = dateString.replaceAll(Matcher.quoteReplacement(m.group(0)), m.group(1));
        }
        return dateString;
    }

    public static void main(String[] args) {

        String dateString = "August 21st, 2012";
        SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy");
        Date emp1joinDate = null;
        try {
            emp1joinDate = sdf.parse(deleteOrdinal(dateString));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

答案 3 :(得分:0)

String dateString = "2011-04-22";
SimpleDateFormat format = new SimpleDateFormat("d MMM, yyyy");

try {
    Date parsed = format.parse(dateString);
}
catch(ParseException pe) {
    System.out.println("ERROR: Cannot parse \"" + dateString + "\"");
}

答案 4 :(得分:0)

我想指出格式应该依赖于Locale ......当然,你可以这样做:

String fromDate = "2011-04-22";
DateFormat incomming = new SimpleDateFormat("yyyy-MM-dd");
DateFormat outgoing = DateFormat.getDateInstance(DateFormat.Long, Locale.US);
try {
  Date parsed = incomming.parse(fromDate);
  String toDate = outgoing.format(parsed);
}
catch (ParseException pe) {
  pe.printStackTrace();
}

当然,您需要传递最终用户的Locale ...而不是Locale.US。

顺便说一句。您可能希望使用Apache Commons Lang's FastDateFormat而不是糟糕的SimpleDateFormat。如果您正在执行许多与日期相关的操作,请同时找到DateUtils