我正在尝试将日期字符串解析为日期。我试过以下代码
public class convertDate
{
public static void main(String args[])
{
String strlastruntime ="16/06/2016 9:17:00 AM",dateFormat ="MM/dd/yyyy hh:mm:ss a";
try
{
strlastruntime = strlastruntime.trim();
System.out.println("strlastruntime = "+strlastruntime+" dateFormat = "+dateFormat);
java.util.Locale l = java.util.Locale.US;
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(dateFormat,l);
//System.out.println("formatter = "+formatter);
java.util.Date date = formatter.parse( strlastruntime );
System.out.println("date = "+date);
long time = date.getTime();
System.out.println("time = "+time);
}
catch(java.text.ParseException ee)
{
ee.printStackTrace();
System.out.println(ee);
}
}
}
但是,上面的输入字符串输出错误 我在运行代码时得到了这个输出:
strlastruntime = 16/06/2016 9:17:00 AM dateFormat = MM/dd/yyyy hh:mm:ss a
date = Thu Apr 06 09:17:00 IST 2017
time = 1491450420000
所以,请帮我找到解决方案..
答案 0 :(得分:2)
更改dateFormat ="MM/dd/yyyy hh:mm:ss a";
到dateFormat ="dd/MM/yyyy hh:mm:ss a";
完整代码
public static void main(String args[])
{
String strlastruntime ="16/06/2016 9:17:00 AM",dateFormat ="dd/MM/yyyy hh:mm:ss a";
try
{
strlastruntime = strlastruntime.trim();
System.out.println("strlastruntime = "+strlastruntime+" dateFormat = "+dateFormat);
java.util.Locale l = java.util.Locale.US;
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(dateFormat,l);
//System.out.println("formatter = "+formatter);
java.util.Date date = formatter.parse( strlastruntime );
System.out.println("date = "+date);
long time = date.getTime();
System.out.println("time = "+time);
}
catch(java.text.ParseException ee)
{
ee.printStackTrace();
System.out.println(ee);
}
}
输出:
strlastruntime = 16/06/2016 9:17:00 AM dateFormat = dd/MM/yyyy hh:mm:ss a
date = Thu Jun 16 09:17:00 IST 2016
time = 1466048820000