I have time stamp as 29-NOV-11 06.05.41.831000000 AM
Using SimpleDateFormat , i cannot really extract millisecond (.831000000) ....831 is millisecond (and i don't know why those 000000. But thats coming from different source. No control on that.)
I have time stamp as 29-NOV-11 06.05.41.831000000 AM
Using SimpleDateFormat , i cannot really extract millisecond (.831000000) ....831 is millisecond (and i don't know why those 000000. But thats coming from different source. No control on that.)
The extra digits are nano-second. You can't include these in SimpleDateFormat or the standard libraries. The simplest thing to do in you case is to remove them before parsing the date/time.
Parse your date-time string into the OffsetDateTime
using the timezone offset of UTC and convert the result into an Instant
.
You can convert the Instant
into milliseconds using Instant#toEpochMilli
.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("d-MMM-uu h.m.s.n a")
.toFormatter(Locale.ENGLISH)
.withZone(ZoneOffset.UTC);
OffsetDateTime odt = OffsetDateTime.parse("29-NOV-11 06.05.41.831000000 AM", dtf);
Instant instant = odt.toInstant();
long millis = instant.toEpochMilli();
System.out.println(millis);
}
}
Output:
1322546741831
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
If the timestamp is represented by a string you could use a regular expression to parse out the extra zeroes.
A working solution... A fairly strict regex for this is quite long-winded as you see.
String input = "29-NOV-11 06.05.41.831000000 AM";
input = input
.replaceFirst(
"(\\d+-\\w+-\\d+\\s\\d+\\.\\d+\\.\\d+\\.\\d{3})\\d{6}(\\s(\\w+))",
"$1$2");
try {
SimpleDateFormat sdf = new SimpleDateFormat(
"dd-MMM-yy HH.mm.ss.SSS aa");
Date date = sdf.parse(input);
System.out.println(sdf.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
You could just use substr if the strings are always fixed width and you consider regex a bit of overkill.
input = input.substring(0, 22) + input.substring(28, 31);