While trying to transform the date format I get an exception:unparseable date and don't know how to fix this problem.
I am receiving a string which represents an event date and would like to display this date in different format in GUI.
What I was trying to do is the following:
private String modifyDateLayout(String inputDate){
try {
//inputDate = "2010-01-04 01:32:27 UTC";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
} catch (ParseException e) {
e.printStackTrace();
return "15.01.2010";
}
}
Run Code Online (Sandbox Code Playgroud)
Anyway the line
String modifiedDateString = originalDate.toString();
Run Code Online (Sandbox Code Playgroud)
is dummy. I would like to get a date string in the following format:
dd.MM.yyyy HH:mm:ss
and the input String example is the following:
2010-01-04 01:32:27 UTC
Does anyone know how to convert the example date (String) above into a String format dd.MM.yyyy HH:mm:ss?
Thank you!
编辑:我修复了错误的输入日期格式,但它仍然无法正常工作.上面是粘贴的方法,下面是调试会话的屏幕图像.
替代文字http://img683.imageshack.us/img683/193/dateproblem.png
#Update 我跑了
String[] timezones = TimeZone.getAvailableIDs();
Run Code Online (Sandbox Code Playgroud)
并且数组中有UTC字符串.这是一个奇怪的问题.
我做了一个有效的肮脏黑客:
private String modifyDateLayout(String inputDate){
try {
inputDate = inputDate.replace(" UTC", "");
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(inputDate);
return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
} catch (ParseException e) {
e.printStackTrace();
return "15.01.2010";
}
}
Run Code Online (Sandbox Code Playgroud)
但我仍然希望在不缩短时区的情况下转换原始输入.
此代码是使用JDK 1.6为Android手机编写的.
Bal*_*usC 50
你在这里基本上做的是依靠Date#toString()已经有固定模式的东西.要将Java Date对象转换为另一种人类可读的String模式,您需要SimpleDateFormat#format().
private String modifyDateLayout(String inputDate) throws ParseException{
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,这里只能抛出"不可解析的日期"异常SimpleDateFormat#parse().这意味着它inputDate不是预期的模式"yyyy-MM-dd HH:mm:ss z".您可能需要修改模式以匹配inputDate实际模式.
更新:好的,我做了一个测试:
public static void main(String[] args) throws Exception {
String inputDate = "2010-01-04 01:32:27 UTC";
String newDate = new Test().modifyDateLayout(inputDate);
System.out.println(newDate);
}
Run Code Online (Sandbox Code Playgroud)
这正确打印:
03.01.2010 21:32:27
Run Code Online (Sandbox Code Playgroud)
(我在GMT-4上)
更新2:根据你的编辑,你真的得到了ParseException.最可疑的部分将是时区UTC.这在Java环境中实际上是否已知?您使用的Java版本和操作系统版本是什么?检查TimeZone.getAvailableIDs().必须有一个UTC之间英寸
| 归档时间: |
|
| 查看次数: |
161230 次 |
| 最近记录: |