我正在尝试使用 Java 的 SimpleDateFormat
将字符串转换为正确的日期格式。由于某种原因,它不适用于某些月份,例如“三月”、“五月”、“十月”和“十二月”。有人可以帮助我吗?其他月份都可以正常使用。
import java.sql.Date;
import java.text.SimpleDateFormat;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
public class test {
public static void main(String args[]) throws java.text.ParseException {
try {
SimpleDateFormat parse = new SimpleDateFormat("dd. MMM yyyy hh:mm:ss");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//why this doesn't work with certain months like Mar, May, Oct, and Dec? otherwise it works fine
String dateTime = "01. Jun 2010 15:30:32";
//String dateTime = "07. Mar 2011 15:20:10";
//String dateTime = "07. May 2011 15:20:10";
//String dateTime = "07. Oct 2011 15:20:10";
//String dateTime = "07. Dec 2011 15:20:10";
java.util.Date parsed =parse.parse(dateTime);
System.out.println("formatted: " + formatter.format(parsed));
} catch(ParseException e) {
System.out.println("Caught " + e);
}
}
}
最佳答案
您需要在 SimpleDateFormat
上设置区域设置,否则月份名称将使用平台默认区域设置。您可以通过将其传递为 2nd argument to the SimpleDateFormat
constructor 来做到这一点。如果您想使用英文格式的月份名称,请传递 Locale.ENGLISH
.
new SimpleDateFormat("dd. MMM yyyy hh:mm:ss", Locale.ENGLISH);
顺便说一句,您可以通过以下方式了解您的平台默认区域设置
System.out.println(Locale.getDefault());
这可以在操作系统级别(例如,在 Windows 控制面板中)并作为 JVM 参数进行配置。
关于java - 将字符串转换为格式化日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5581488/