嗨,对于所有我有问题将日期和时间转换为毫秒可以任何人请帮助我,它没有代码中的错误,但它以毫秒返回错误的日期和时间
这是我转换的日期: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;
}
答案 0 :(得分:2)
c.set行没有任何意义:
c.set(sdf.YEAR_FIELD, sdf.MONTH_FIELD, sdf.DATE_FIELD, sdf.HOUR0_FIELD, sdf.MINUTE_FIELD, sdf.SECOND_FIELD);
这应该会给你一个想法:
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());
输出:
1299002115000000000
Tue Mar 01 12:55:15 EST 2011
顺便说一下,你永远不会访问参数s。