简单的日期格式不能正确解析日期
问题描述:
当我使用简单的日期格式解析某些日期(时间)时,下面的代码给了我比预期时间多五个小时的时间。我正在解析毫秒到字符串。我正在解析一些媒体文件的持续时间。例如,当我的媒体文件实际上是10分钟时,它会提供5小时10分钟。问题是什么?简单的日期格式不能正确解析日期
public static String formatTime(String time) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("H:mm:ss");
Date date = new Date(Long.parseLong(time));
return simpleDateFormat.format(date);
答
您不应该用Date
来代表持续时间。如果Time
是媒体文件的持续时间(以毫秒为单位),那么Date date = new Date(Long.parseLong(Time));
将构建一个日期,该日期在1970年1月1日00:00之后的许多毫秒,在您的情况下将是当天的00:10。
恐怕您必须手动将您的毫秒解析为几小时,几分钟和几秒钟,然后使用String.format("%d:%02d:%02d",hours,minutes,seconds)
进行格式化。
答
我用这种方式它的正常工作
public static String FormatTime(String Time) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
Date d=new Date(Long.parseLong(Time));
String formatted=simpleDateFormat.format(d);
if (Long.parseLong(Time) > 3600000&&Long.parseLong(Time)<7200000) {
formatted=String.format("%d %s",1,formatted);
}
else if (Long.parseLong(Time)>=7200000&&Long.parseLong(Time)<10800000){
formatted=String.format("%d %s",2,formatted);
}
return formatted;
}
你可以添加'Time'输入值的一些例子吗? – Henrik
添加一些时间参数,你传递的是什么? –
您正在使用java.util.Date对象来存储时间(小时,分钟,秒),但Date对象不适合仅存储时间。 – Jesper