我在将日期和时间转换为毫秒时遇到问题。代码中没有错误,但它以毫秒为单位返回错误的日期和时间。
这是我正在转换的日期:2011-03-01 17:55:15
它给了我这个数字:-679019461843345152
。
这是我正在使用的代码:
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;
}