I have written this sample program where I want to convert a date into another format. I don't see the expected date when using simple date format.
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();
}
}
}
I see the following outputs. The first logic is using simple date format and the second one is manual translation.
Using SDF 2015-04-09 17:30:05.000862
Manual Translation 2015-04-09 17:18:48.677862000
So How to make the simple date format to output a exactly similar value like the manual one
The value 677862
is being interpreted as milliseconds, as per the SimpleDateFormat
javadocs , not as microseconds. That is 677 seconds, 862 milliseconds. The seconds part is 11 minutes and 17 seconds, which is added to 17.18.48
to become 17.30.05
.
To work with the S
format, you will need 3 digits for the milliseconds, not 6. You will need to truncate your string to 3 digits past the last decimal point.
It would appear that you can't use 6 digits for the milliseconds. Your program is 11 minutes and 17 seconds off. 660 seconds = 11 minutes and you have 17 seconds off. So its just converting your input into minutes from seconds since it can't accept more than 3 milliseconds digits.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.