I am having a problem with converting the date and time to milliseconds. There are no errors in the code but it's returning the wrong date and time in milliseconds.
This is the date that I'm converting: 2011-03-01 17:55:15
and it gives me this number: -679019461843345152
.
This is the code I'm using:
public long getDate(String s)
{
//this is returning a timestamp but the wrong ones!!!
String[] formats = new String[]{
// "yyyy-MM-dd",
"yyyy-MM-dd HH:mm:ss"
// "yyyy-MM-dd HH:mmZ",
//"yyyy-MM-dd HH:mm:ss.SSSZ",
};
SimpleDateFormat sdf = null;
String st;
for (String format : formats)
{
sdf = new SimpleDateFormat(format, Locale.US);
//System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
st = new String(sdf.format(new Date(0)));
System.err.format(format, st);
}
// compute nanoseconds from y, m...
//return that number
Calendar c = Calendar.getInstance();
c.set(sdf.YEAR_FIELD, sdf.MONTH_FIELD, sdf.DATE_FIELD, sdf.HOUR0_FIELD, sdf.MINUTE_FIELD, sdf.SECOND_FIELD);
return c.getTimeInMillis() * 1000000;
}
The line c.set does not make any sense:
c.set(sdf.YEAR_FIELD, sdf.MONTH_FIELD, sdf.DATE_FIELD, sdf.HOUR0_FIELD, sdf.MINUTE_FIELD, sdf.SECOND_FIELD);
This should give you an idea:
Calendar c = Calendar.getInstance();
try {
dt = sdf.parse("2011-03-01 17:55:15");
} catch (ParseException e) {
System.err.println("There's an error in the Date!");
return null;
}
Date dt = sdf.parse("2011-03-01 17:55:15");
c.setTime(dt);
System.out.println( c.getTimeInMillis() * 1000000);
System.out.println(dt.toString());
outputs:
1299002115000000000
Tue Mar 01 12:55:15 EST 2011
BTW, you are never accessing the parameter s.