SimpleDateFormat 显示分钟、秒和毫秒错误
SimpleDateFormat showing minutes, seconds and milliseconds wrong
我编写了这个示例程序,我想在其中将日期转换为另一种格式。使用简单日期格式时,我看不到预期日期。
public class TestDate {
/**
* @param args
*/
public static void main(String[] args) {
SimpleDateFormat originalformat = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSSSSS");
SimpleDateFormat targetformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
try {
//Use Simple Date Format
Date date = originalformat.parse("2015-04-09-17.18.48.677862");
System.out.println("Using SDF "+targetformat.format(date));
//Use Manual Translation
String eventTime = "2015-04-09-17.18.48.677862";
StringBuffer timeBuffer = new StringBuffer();
for (int i = 0; i < eventTime.length(); i++) {
if (i == 10) {
timeBuffer.append(" ");
continue;
} else if (i == 13 || i == 16) {
timeBuffer.append(":");
continue;
} else {
timeBuffer.append(eventTime.charAt(i));
}
}
timeBuffer.append("000");
String transformedTime = timeBuffer.toString().trim();
System.out.println("Manual Translation "+transformedTime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我看到了以下输出。第一个逻辑是使用简单的日期格式,第二个逻辑是手动翻译。
Using SDF 2015-04-09 17:30:05.000862
Manual Translation 2015-04-09 17:18:48.677862000
那么如何使简单的日期格式输出与手动日期格式完全相似的值
根据 SimpleDateFormat
javadocs,值 677862
被解释为毫秒,而不是微秒。那是 677 秒,862 毫秒。秒部分是11分17秒,加上17.18.48
变成17.30.05
.
要使用 S
格式,您需要 3 位数的毫秒数,而不是 6 位数。您需要将字符串截断为小数点后的 3 位数。
您似乎不能使用 6 位数字表示毫秒。您的程序暂停 11 分 17 秒。 660 秒 = 11 分钟,您有 17 秒的休息时间。所以它只是将您的输入从秒转换为分钟,因为它不能接受超过 3 毫秒的数字。
我编写了这个示例程序,我想在其中将日期转换为另一种格式。使用简单日期格式时,我看不到预期日期。
public class TestDate {
/**
* @param args
*/
public static void main(String[] args) {
SimpleDateFormat originalformat = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSSSSS");
SimpleDateFormat targetformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
try {
//Use Simple Date Format
Date date = originalformat.parse("2015-04-09-17.18.48.677862");
System.out.println("Using SDF "+targetformat.format(date));
//Use Manual Translation
String eventTime = "2015-04-09-17.18.48.677862";
StringBuffer timeBuffer = new StringBuffer();
for (int i = 0; i < eventTime.length(); i++) {
if (i == 10) {
timeBuffer.append(" ");
continue;
} else if (i == 13 || i == 16) {
timeBuffer.append(":");
continue;
} else {
timeBuffer.append(eventTime.charAt(i));
}
}
timeBuffer.append("000");
String transformedTime = timeBuffer.toString().trim();
System.out.println("Manual Translation "+transformedTime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我看到了以下输出。第一个逻辑是使用简单的日期格式,第二个逻辑是手动翻译。
Using SDF 2015-04-09 17:30:05.000862
Manual Translation 2015-04-09 17:18:48.677862000
那么如何使简单的日期格式输出与手动日期格式完全相似的值
根据 SimpleDateFormat
javadocs,值 677862
被解释为毫秒,而不是微秒。那是 677 秒,862 毫秒。秒部分是11分17秒,加上17.18.48
变成17.30.05
.
要使用 S
格式,您需要 3 位数的毫秒数,而不是 6 位数。您需要将字符串截断为小数点后的 3 位数。
您似乎不能使用 6 位数字表示毫秒。您的程序暂停 11 分 17 秒。 660 秒 = 11 分钟,您有 17 秒的休息时间。所以它只是将您的输入从秒转换为分钟,因为它不能接受超过 3 毫秒的数字。