返回时间戳(以毫秒为单位)
我在将日期和时间转换为毫秒时遇到问题。代码中没有错误,但它返回错误的日期和时间(以毫秒为单位)。
这是我要转换的日期: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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
c.set 行没有任何意义:
这应该给您一个想法:
输出:
顺便说一句,您永远不会访问参数 s。
The line c.set does not make any sense:
This should give you an idea:
outputs:
BTW, you are never accessing the parameter s.