Reputation: 297
I'm trying to parse date string into date. I have tried following code
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);
}
}
}
But, I am getting wrong output for the above input string I am getting this output while running the code:
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
So, please help me to find the solution..
Upvotes: 0
Views: 57
Reputation: 13844
change dateFormat ="MM/dd/yyyy hh:mm:ss a";
to dateFormat ="dd/MM/yyyy hh:mm:ss a";
full code
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);
}
}
output:
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
Upvotes: 2