I have this code:
SimpleDateFormat sDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
I know that this code return hour, minute, second in the time. How i can get also the millisecond and microsecond??
You won't have microseconds, because a Date stores the number of milliseconds since Jan. 1 1970. For the milliseconds, use S
, as documented in the javadoc.
The only way to get micro-seconds is to parse the string yourself. Note: Date
should be used to store micro-seconds, but you can use a long
. (which you can also use for milli-seconds or nano-seconds)
private static final String YEARS_TO_MINUTES = "yyyy-MM-dd HH:mm";
private static final SimpleDateFormat YEARS_TO_MINUTES_SDF = new SimpleDateFormat(YEARS_TO_MINUTES);
public static long parseMicroSeconds(String text) throws ParseException {
long timeMS;
synchronized (YEARS_TO_MINUTES_SDF) {
timeMS = YEARS_TO_MINUTES_SDF.parse(text.substring(0, YEARS_TO_MINUTES.length())).getTime();
}
long microSecs = 0;
if (text.length() > YEARS_TO_MINUTES.length() + 1) {
double secs = Double.parseDouble(text.substring(YEARS_TO_MINUTES.length() + 1));
microSecs = (long) (secs * 1e6 + 0.5);
}
return timeMS * 1000 + microSecs;
}
public static String formatMicroSeconds(long timeMicroSeconds) {
String dateTime;
synchronized (YEARS_TO_MINUTES_SDF) {
dateTime = YEARS_TO_MINUTES_SDF.format(new Date(timeMicroSeconds / 1000));
}
long secs = timeMicroSeconds % 60000000;
return dateTime + String.format(":%09.6f", secs / 1e6);
}
public static void main(String... args) throws ParseException {
String dateTime = "2011-01-17 19:27:59.999650";
long timeUS = parseMicroSeconds(dateTime);
for (int i = 0; i < 5; i++)
System.out.println(formatMicroSeconds(timeUS += 175));
}
prints
2011-01-17 19:27:59.999825
2011-01-17 19:28:00.000000
2011-01-17 19:28:00.000175
2011-01-17 19:28:00.000350
2011-01-17 19:28:00.000525
You can do similarly if you need nano-timings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With